【问题标题】:R: how to select only continuous numeric columnsR:如何只选择连续的数字列
【发布时间】:2021-06-25 01:16:27
【问题描述】:

这可能更像是一个理论问题而不是编码问题。

我正在尝试编写一个闪亮的应用程序,它将遍历数据框的连续数字列并对这些列执行测试。该应用程序允许用户上传自己的数据框,所以我不知道它会提前是什么样子。我知道我可以使用 dplyr 包通过以下方式仅选择数字列

library(dplyr)
data <- data %>%
        select(where(is.numeric))

这可行,但离散的数字列也会保留。我想不出一个只选择连续列的好方法。

我曾想过尝试做一些事情,比如只选择模式重复次数小于数据帧长度的某个比例的列。或者可能像唯一值的数量需要大于模式重复的次数。但这些似乎都不能很好地概括。而且他们也不会摆脱 id 列。

感谢任何想法,谢谢。

【问题讨论】:

  • 如果离散变量编码为整数或因子,如果您询问is.double,您将返回 FALSE

标签: r selection continuous


【解决方案1】:

有一个库schoolmath 带有is.decimalis.whole 函数:

library(schoolmath)
x <- c(1, 1.5)
any(is.decimal(x))
TRUE

因此您可以使用apply 处理您的数据框:

decimal_cols <- apply(df, 2, function(x) any(is.decimal(x))

返回的 TRUE 的索引值将是具有十进制值的列。

【讨论】:

  • 谢谢,我已经接受了这个答案。
【解决方案2】:

如何定义is_continuous:

# one of them:
is_discrete   <- function(vec) all(is.numeric(x)) && all(x %% 1 == 0)
is_discrete   <- function(vec, tolerance=0.000001) all(is.numeric(x)) && all(min(abs(c(x %% 1, x %% 1 - 1))) < tolerance)

# and then:
is_continuous <- function(vec) all(is.numeric(vec)) && !is_discrete(vec)

然后,你可以这样做:

library(dplyr)
data <- data %>%
        select(where(is_continuous))

【讨论】:

    【解决方案3】:

    您是否考虑过将离散变量转化为因子?这是一个可能有您正在寻找的解决方案的示例:

    library(dplyr)
    
    head(mtcars)
    
    > head(mtcars)
                       mpg cyl disp  hp drat    wt  qsec vs am gear carb
    Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    
    Then I turn cyl into a factor and then select only numeric columns apart from the factor which is cyl:
    
    mtcars2 %>%
      as_tibble() %>%
      mutate(cyl = as.factor(cyl)) %>%
      select(where( ~ !is.factor(.x) && is.numeric(.x))) %>%
      slice_head(n = 5)
    
    # A tibble: 5 x 10
        mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb
      <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    1  21     160   110  3.9   2.62  16.5     0     1     4     4
    2  21     160   110  3.9   2.88  17.0     0     1     4     4
    3  22.8   108    93  3.85  2.32  18.6     1     1     4     1
    4  21.4   258   110  3.08  3.22  19.4     1     0     3     1
    5  18.7   360   175  3.15  3.44  17.0     0     0     3     2
    
    

    我编辑了我的能力并且只使用了select 函数。但是,我假设您的离散变量的范围有限,例如 cyl 这里。如果你能分享你的数据让我们看看它们到底是什么,也许会更好。

    【讨论】:

    • 感谢您的回复。我正在编写应用程序,以便用户可以上传任何数据框,所以我不会事先知道哪些列是因素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多