问题描述
我有大量的数据框架,不同数量的列和行。我将搜索数据帧中的给定向量的值,并删除与该给定向量的值匹配的单元格行。我希望将其作为一个函数,因为我必须在多个可变行和列的数据框上运行它,并且我希望避免循环的。
例如
ff< -structure(list(j.1 = 1 :13,j.2 = 2:14,j.3 = 3:15),.Names = c(j.1,j.2,j.3),row.names = c NA,-13L),class =data.frame)
删除所有具有单元格的行包含值 8,9,10
我想我可以使用 ff [! %c(8,9,10)中的ff [,1]%,%c(8,9)中的
或子集(ff,!ff [,1] ,10))
但是为了从数据集中删除所有的值,我必须解析每一列(大概用一个为
循环,我想避免的东西)。
有没有其他(更清洁)的方式?
非常感谢
解决方案 应用
您的测试到每一行:
保持< - apply(ff,1,function(x)!any(x%in%8:10))
pre>
其中给出一个布尔向量。然后用子集:
ff [保持,]
j.1 j.2 j。 3
1 1 2 3
2 2 3 4
3 3 4 5
4 4 5 6
5 5 6 7
11 11 12 13
12 12 13 14
13 13 14 15
>
I have big data frame with various numbers of columns and rows. I would to search the data frame for values of a given vector and remove the rows of the cells that match the values of this given vector. I'd like to have this as a function because I have to run it on multiple data frames of variable rows and columns and I wouls like to avoid for
loops.
for example
ff<-structure(list(j.1 = 1:13, j.2 = 2:14, j.3 = 3:15), .Names = c("j.1","j.2", "j.3"), row.names = c(NA, -13L), class = "data.frame")
remove all rows that have cells that contain the values 8,9,10
I guess i could use ff[ !ff[,1] %in% c(8, 9, 10), ]
or subset(ff, !ff[,1] %in% c(8,9,10) )
but in order to remove all the values from the dataset i have to parse each column (probably with a for
loop, something i wish to avoid).
Is there any other (cleaner) way?
Thanks a lot
解决方案 apply
your test to each row:
keeps <- apply(ff, 1, function(x) !any(x %in% 8:10))
which gives a boolean vector. Then subset with it:
ff[keeps,]
j.1 j.2 j.3
1 1 2 3
2 2 3 4
3 3 4 5
4 4 5 6
5 5 6 7
11 11 12 13
12 12 13 14
13 13 14 15
>
这篇关于删除其单元格与给定向量匹配的数据帧行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!