问题描述
我有一个数据框,其中有多个列(超过 30 个)保存在一个列表中.我想对所有这些列应用相同的标准,而无需为每一列编写每个代码.我有下面的例子来帮助更好地理解我的问题
I have a dataframe in which there are multiple columns (more than 30) that is saved in a list. I would like to apply the same criteria for all those columns without writing each code for each columns. I have example below to help understand my problem better
A<-c("A","B","C","D","E","F","G","H","I")
B<-c(0,0,0,1,2,3,0,0,0)
C<-c(0,1,0,0,1,2,0,0,0)
D<-c(0,0,0,0,1,1,0,1,0)
E<-c(0,0,0,0,0,0,0,1,0)
data<-data.frame(A,B,C,D,E)
假设我以上面的 df 为例,我已经保存了 cols 列表如下
Let say I have the above df as an example and I have saved the list of cols as below
list <- c("B","C","D","E")
我想使用符合以下条件的列
I would like to use those cols with the same criteria as below
setDT(data)[B>=1 | C>=1 | D>=1 | E>=1]
得到如下结果
A B C D E
1: B 0 1 0 0
2: D 1 0 0 0
3: E 2 1 1 0
4: F 3 2 1 0
5: H 0 0 1 1
但是,有没有办法在不编写每个单独的列条件(例如 B>=1 | C>=1 ....)的情况下获得上述答案,因为我在实际数据中有 30 多个列.非常感谢
However, is there a way to get the above answer without writing each individual column criteria (e.g. B>=1 | C>=1 ....) since I have more than 30 cols in the actual data. Thanks a lot
推荐答案
对于检查一行中是否至少有一个值至少为 1 的具体示例,您可以使用 rowSums
For your specific example of checking if at least one value in a row is at least 1, you could use rowSums
data[rowSums(data[,-1]) > 0, ]
# A B C D E
# 2 B 0 1 0 0
# 4 D 1 0 0 0
# 5 E 2 1 1 0
# 6 F 3 2 1 0
# 8 H 0 0 1 1
如果您有其他标准,您不妨考虑在 apply
中使用 any
If you have other criteria in mind, you might as well consider using any
within apply
ind <- apply(data[,-1], 1, function(x) {any(x >= 1)})
data[ind,]
# A B C D E
# 2 B 0 1 0 0
# 4 D 1 0 0 0
# 5 E 2 1 1 0
# 6 F 3 2 1 0
# 8 H 0 0 1 1
这篇关于根据 R 中的相同条件过滤多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!