R:根据较少行中的缺失值删除多行 [英] R: remove multiple rows based on missing values in fewer rows
问题描述
我有一个 R 数据框,其中包含来自多个主题的数据,每个主题都经过多次测试.为了对集合进行统计,有一个主题因子(id")和每个观察的一行(由因子会话"给出).即
I have an R data frame with data from multiple subjects, each tested several times. To perform statistics on the set, there is a factor for subject ("id") and a row for each observation (given by factor "session"). I.e.
print(allData)
id session measure
1 1 7.6
2 1 4.5
3 1 5.5
1 2 7.1
2 2 NA
3 2 4.9
在上面的示例中,考虑到度量"列在其中 id==2 的行之一中包含 NA,是否有一种简单的方法可以删除所有 id==2 的行?
In the above example, is there a simple way to remove all rows with id==2, given that the "measure" column contains NA in one of the rows where id==2?
更一般地说,因为我实际上有很多度量(列)和每个主题的四个会话(行),有没有一种优雅的方法来删除具有给定id"因子级别的所有行,假设(至少)具有此id"级别的行之一在一列中包含 NA?
More generally, since I actually have a lot of measures (columns) and four sessions (rows) for each subject, is there an elegant way to remove all rows with a given level of the "id" factor, given that (at least) one of the rows with this "id"-level contains NA in a column?
我的直觉是,可能有一个内置函数可以比我当前的解决方案更优雅地解决这个问题:
I have the intuition that there could be a build-in function that could solve this problem more elegantly than my current solution:
# Which columns to check for NA's in
probeColumns = c('measure1','measure4') # Etc...
# A vector which contains all levels of "id" that are present in rows with NA's in the probeColumns
idsWithNAs = allData[complete.cases(allData[probeColumns])==FALSE,"id"]
# All rows that isn't in idsWithNAs
cleanedData = allData[!allData$id %in% idsWithNAs,]
谢谢,/乔纳斯
推荐答案
您可以使用 plyr
包中的 ddply
函数来 1) 按 id
, 2)如果子 data.frame 在您选择的列中包含 NA
或 data.frame 本身,则应用一个将返回 NULL
的函数,并且 3) 将所有内容连接回去进入数据框.
You can use the ddply
function from the plyr
package to 1) subset your data by id
, 2)
apply a function that will return NULL
if the sub data.frame contains NA
in the columns of your choice, or the data.frame itself otherwise, and 3) concatenate everything back into a data.frame.
allData <- data.frame(id = rep(1:4, 3),
session = rep(1:3, each = 4),
measure1 = sample(c(NA, 1:11)),
measure2 = sample(c(NA, 1:11)),
measure3 = sample(c(NA, 1:11)),
measure4 = sample(c(NA, 1:11)))
allData
# id session measure1 measure2 measure3 measure4
# 1 1 1 3 7 10 6
# 2 2 1 4 4 9 9
# 3 3 1 6 6 7 10
# 4 4 1 1 5 2 3
# 5 1 2 NA NA 5 11
# 6 2 2 7 10 6 5
# 7 3 2 9 8 4 2
# 8 4 2 2 9 1 7
# 9 1 3 5 1 3 8
# 10 2 3 8 3 8 1
# 11 3 3 11 11 11 4
# 12 4 3 10 2 NA NA
# Which columns to check for NA's in
probeColumns = c('measure1','measure4')
library(plyr)
ddply(allData, "id",
function(df)if(any(is.na(df[, probeColumns]))) NULL else df)
# id session measure1 measure2 measure3 measure4
# 1 2 1 4 4 9 9
# 2 2 2 7 10 6 5
# 3 2 3 8 3 8 1
# 4 3 1 6 6 7 10
# 5 3 2 9 8 4 2
# 6 3 3 11 11 11 4
这篇关于R:根据较少行中的缺失值删除多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!