问题描述
我想知道是否有更简单的方法来设置数据框的整型列。
我的目标是在不触及纯整数列(在我的例子中包含0或1)的情况下修改data.Frame中的数字列。整数列最初是因子级别,变成了虚拟变量,应该保持原样。所以我想暂时删除它们。
为了区分数字列和整型列,我使用了此处的OP版本(Check if the number is integer)。
但is.wholenumber
返回一个TRUE/FALSE矩阵,而不是像is.numeric
那样每列返回一个值,因此sapply(mtcars, is.wholenumber)
对我没有帮助。我想出了以下解决方案,但我想一定有更简单的方法?
data(mtcars)
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
integer_column_names <- apply(is.wholenumber(mtcars), 2, mean) == 1
numeric_df <- mtcars[, !integer_column_names]
推荐答案
您可以使用dplyr
来实现此目的,如here
library(dplyr)
is_whole <- function(x) all(floor(x) == x)
df = select_if(mtcars, is_whole)
或以R为单位
df = mtcars[ ,sapply(mtcars, is_whole)]