我想知道是否有一种更简单的方法来设置data.frame的整数列。
我的目标是修改data.frame中的数字列,而不触及纯整数列(在我的情况下为0或1)。整数列最初是因子水平,变成了虚拟变量,应保持原样。因此,我想暂时将其删除。
为了从整数列中区分数值,我在这里使用了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)]