【问题标题】:Run chi-square test in all columns for a data_frame using dplyr使用 dplyr 在 data_frame 的所有列中运行卡方检验
【发布时间】:2018-01-24 18:16:55
【问题描述】:

有几个类似的问题可以获取chi-square 结果,但这解决了我的问题。我想从chi-square 测试中为data_frame 中的所有列计算p.values,并将它们存储在原始data_frame 中的列中。会有重复的值,我很好。最终,我想select data_frame 中的所有列,其 p.value 低于 x 与我选择的变量。

require(dplyr)

my_df <- data_frame(
  one_f = sample(LETTERS[1:5],100,T),
  two_f = sample(LETTERS[4:5],100,T),
  three_f = sample(LETTERS[5],100,T)
)
my_df %>% 
  head()

my_df %>% 
  summarise_all(funs(chisq.test(.,my_df$two_f)$p.value))

告诉我这个错误:

Error in summarise_impl(.data, dots) : 
  Evaluation error: 'x' and 'y' must have at least 2 levels.


my_df %>% 
  mutate_if(n_distinct>1,fun(chisq.test(.,my_df$two_f)$p.value))

告诉我这个错误:

Error in n_distinct > 1 : 
  comparison (6) is possible only for atomic and list types

我正在寻找这样的东西。

my_df %>% 
      mutate(p.value = sample(c(0.043,0.87,0.00),nrow(.),T)) %>% 
      head()

然后我计划使用gatherfilter 然后spread 根据我的chi-square 测试得到显着相关的变量。

我想

my_df %>% filter(foo,bar >= 0.05)#function that finds p.values and filters by 
# alpha level

将是我的最终目标。

【问题讨论】:

  • 你的意思是在标题中?
  • 进程中断是因为three_f 列只有一个不同的值E。您可以有一个过程来删除这些列,然后对其余列执行测试。
  • 是的,我尝试使用 mutate_if(n_distinct&gt;1, . . .) 是为了克服这个问题,但它会抛出上面代码中列出的第二条错误消息。
  • n_distinct 按行工作,有或没有分组来计算不同的行。它不明白你想将它应用到每一列。我将发布一个替代(但显然不是唯一的)解决方案。
  • 您的示例数据有 100 条记录和三个变量。您想对每个(符合条件的)变量执行chisq.test 并将(最多3个)p值...放在同一个data_frame的变量中?我想不出任何有意义的方法。

标签: r dplyr


【解决方案1】:
require(dplyr)
require(tidyr)

my_df <- data_frame(
  one_f = sample(LETTERS[1:5],100,T),
  two_f = sample(LETTERS[4:5],100,T),
  three_f = sample(LETTERS[5],100,T)
)

# select all column names where the column has more than 1 distinct values
my_df %>% 
  summarise_all(function(x) length(unique(x))) %>%
  gather() %>%
  filter(value > 1) %>%
  pull(key) -> list_cols

# apply function only to those columns
my_df %>% 
  select(list_cols) %>%
  summarise_all(funs(chisq.test(.,my_df$two_f)$p.value))

# # A tibble: 1 x 2
#     one_f                      two_f
#     <dbl>                      <dbl>
#   1 0.880 0.000000000000000000000120

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2013-09-21
    • 1970-01-01
    • 2017-12-02
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多