wilcox.test.formula中的错误(x~group,data = df):分组因子必须正好有2个级别

时间:2018-01-04 02:40:30

标签: r

我有一个像这样的数据框和一百多个这样的列

Group   V1  V2  V3
1   NaN NaN NaN
1   NaN NaN NaN
1   NaN NaN NaN
1   NaN NaN NaN
1   0.12611 10.75   NaN
1   NaN NaN 1.9909
1   0.085867    12.323  2.0125
1   NaN NaN 2.3301
1   NaN NaN NaN
2   0.0574  3.827   NaN
2   0.15607 1.1194  NaN
2   NaN 0.81006 0.77779
2   0.0737  0.35366 NaN
2   0.1265  2.4674  0.82335
2   0.097067    NaN 0.90923
2   0.82887 1.8804  0.96405

当我尝试wilcox.test为每个列工作时 wilcox.test(V1 ~ Group, data = df)

然而,如果我尝试这样申请 wilcox <- apply(df[,-1], 2, function(x) wilcox.test(x ~ Group, data = df)) 它给出了错误:

Error in wilcox.test.formula(x ~ Group, data = df) : 
grouping factor must have exactly 2 levels 

任何人都知道什么是错的?

1 个答案:

答案 0 :(得分:0)

我们需要为那些元素数量较少的情况创建if/else条件。假设这是因为缺少值

library(purrr)
library(dplyr)
df[-1] %>% 
    map(~ tibble(.x, Group = df$Group)) %>%
    map(~ if(sum(!is.na(.$.x))>2 | nrow(.x) > 2) 
             broom::tidy(wilcox.test(.x~Group, data = .) ) else NA)

使用与OP代码相同的方法

apply(df[,-1], 2, function(x) if(sum(!is.na(x)) >2 ) 
                     wilcox.test(x ~ Group, data = df) else NA)