检查数据中的所有值是否都是整数。框列是子集伪变量,也就是列中的所有值都是真的吗?

人气:813 发布:2022-10-16 标签: r integer numeric subset dummy-variable

问题描述

我想知道是否有更简单的方法来设置数据框的整型列。

我的目标是在不触及纯整数列(在我的例子中包含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)]

460