0

我正在尝试进行自动过滤以消除无用的变量。我在一个命令中处理我的数据,该命令使用此命令删除在我的表中重复超过“x”次的任何值

df <- df[, which(apply(df, 2, function(col) !any(table(col) > x)))] 

我现在正在尝试应用相同的东西,但对于 2 个级别,这就是我的数据的样子

df <- structure(list(V1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20), V2 = c(2, 2, 2, 2, 2, 2, 2, 
2, 0, 0, 0, 2, 2, 7, 2, 3, 4, 6, 4, 5, 2), V3 = c(0, 0, 0, 0, 
0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1), level = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor")), .Names = c("V1", 
"V2", "V3", "level"), row.names = c(NA, 21L), class = "data.frame")

我想删除在 A 和 B 两个级别中重复相同值超过 x 次(在本例中为 5 次)的任何变量。我想要的输出是

df2 <- structure(list(V1 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 1L, 
0L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L), V2 = c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 0L, 0L, 0L, 2L, 5L, 7L, 2L, 3L, 4L, 
6L, 4L, 5L, 2L), level = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", 
"B"), class = "factor")), .Names = c("V1", "V2", "level"), class = "data.frame", row.names = c(NA, 
-21L))

我已经subset()根据级别考虑了数据,执行了我之前的命令并再次加入它们,但这似乎是一个很长的路要走。我想不出一个合适的命令来完成这项工作。关于更短的命令的任何想法可以做到这一点?

谢谢,

4

1 回答 1

2

在两列上使用table以获得双向表,然后使用apply并查看any结果表中的行是否具有all TRUE值(即值出现x多次......

#  Two column tables
lens <- lapply( df[ , -ncol(df) ] , function(x) table( x , df$level ) > 5 )

#  Which columns have ANY values that have more repeats in ALL levels
ind <- sapply( lens , function(x) ! any( apply( x , 1 , all ) ) )

#  Subset
df <- df[, ind ]

head( df )
  V1 V2 level
1  1  2     A
2  2  2     A
3  3  2     A
4  4  2     A
5  5  2     A
6  6  2     A
于 2013-09-16T12:58:51.917 回答