我有一个数据框,其中包含来自ANOVA测试的重要字母。我想仅在所有字母都相等时(即,无显着差异)用NA填充字母列
我试过了:
library(dplyr)
df<- data.frame(A=rnorm(5),B=rep("a",5))
df %>% mutate(B = ifelse(length(unique(B)) == 1,NA, B))
这适用于用NA填充,但不适用于用旧值重新填充列:
df2<- data.frame(A=rnorm(5),B=c("b","a","ab","a","b"))
df2 %>% mutate(B = ifelse(length(unique(B)) == 1,NA, B))
A B
1 1.67671299 b
2 0.21659428 b
3 -1.50746338 b
4 0.82024729 b
5 -0.01105568 b
实际上,它不会再次用原始值填充它。我也试过了,但是没有用
df2 %>% mutate_if((length(unique(.)) == 1),list(rep(NA,nrow(df))))
Error: `.p` is invalid.
x `.p` should have the same size as the number of variables in the tibble.
i `.p` is size 1.
i The tibble has 2 columns, non including the grouping variables.
由于您正在执行标量比较,因此请使用if
/else
而不是vectorized ifelse
:
library(dplyr)
df2 %>% mutate(C = if(n_distinct(B) == 1) NA else B)
# A B C
#1 1.6989886 b b
#2 -0.6174008 a a
#3 1.3540749 ab ab
#4 1.1774202 a a
#5 0.8964335 b b
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句