根据所有组中值的长度筛选data.frame中的行
我有这样一个data.frame:根据所有组中值的长度筛选data.frame中的行,r,dataframe,reshape,R,Dataframe,Reshape,我有这样一个data.frame: df<-data.frame( Id = paste0("g",1:6), a= c(6:11), b = c(10:13,NA,NA), c = c(7:10,NA,10), d = c(NA,7:9,NA,13), e= c(NA,6:10), f= c(NA,NA,NA,4:5,NA)) colnames(df)=c("ID",rep("normal",3),rep("patient",3)) > df ID normal normal
df<-data.frame( Id = paste0("g",1:6),
a= c(6:11),
b = c(10:13,NA,NA),
c = c(7:10,NA,10),
d = c(NA,7:9,NA,13),
e= c(NA,6:10),
f= c(NA,NA,NA,4:5,NA))
colnames(df)=c("ID",rep("normal",3),rep("patient",3))
> df
ID normal normal normal patient patient patient
1 g1 6 10 7 NA NA NA
2 g2 7 11 8 7 6 NA
3 g3 8 12 9 8 7 NA
4 g4 9 13 10 9 8 4
5 g5 10 NA NA NA 9 5
6 g6 11 NA 10 13 10 NA
但这些代码对于具有有限组的数据非常有用。我的主要数据有100组(所有组都有3个副本),colnames(df)=paste0(“grp”,sort(rep(1:100,3))
因此,我需要一些简单的代码来过滤具有100个组的data.frame中的行
我的目标:删除每组中至少没有两个值的行。可以执行以下操作:
library(dplyr)
names(df) <- paste0(names(df), 1:ncol(df))
df %>%
filter(
rowSums(!is.na(select(., contains("normal")))) >= 2 &
rowSums(!is.na(select(., contains("patient")))) >= 2
)
库(dplyr)
姓名(df)%
滤器(
行和(!is.na(选择(,包含(“正常”))>=2&
行和(!is.na(选择(,包含(“患者”))>=2
)
我们可以区分“正常”
和“患者”
列,并使用行和选择行
normal_cols <- grep("normal", names(df))
patient_cols <- grep("patient", names(df))
df[rowSums(!is.na(df[normal_cols])) >= 2 & rowSums(!is.na(df[patient_cols])) >= 2,]
# ID normal normal normal patient patient patient
#2 g2 7 11 8 7 6 NA
#3 g3 8 12 9 8 7 NA
#4 g4 9 13 10 9 8 4
#6 g6 11 NA 10 13 10 NA
我们可以使用重塑
获得一个长格式,并查看列和
这类问题的第一条规则是appR适当的列名,即
资料
df
normal_cols <- grep("normal", names(df))
patient_cols <- grep("patient", names(df))
df[rowSums(!is.na(df[normal_cols])) >= 2 & rowSums(!is.na(df[patient_cols])) >= 2,]
# ID normal normal normal patient patient patient
#2 g2 7 11 8 7 6 NA
#3 g3 8 12 9 8 7 NA
#4 g4 9 13 10 9 8 4
#6 g6 11 NA 10 13 10 NA
fx = function(x) {length(x[!is.na(x)])>=2}
subset(df, apply(df[normal_cols], 1,fx) & apply(df[patient_cols], 1,fx))
names(df) <- c("ID", paste(rep(c("normal", "patient"), each=3), 1:3, sep="."))
r <- reshape(df, idvar="ID", direction="long", varying=list(2:4, 5:7), times=1:3)
s <- by(r[-1], r$ID, function(i) all(colSums(i, na.rm=TRUE) > 2))
df[s, ]
# ID normal normal normal patient patient patient
# 2 g2 7 11 8 7 6 NA
# 3 g3 8 12 9 8 7 NA
# 4 g4 9 13 10 9 8 4
# 6 g6 11 NA 10 13 10 NA
df <- structure(list(Id = structure(1:6, .Label = c("g1", "g2", "g3",
"g4", "g5", "g6"), class = "factor"), a = 6:11, b = c(10L, 11L,
12L, 13L, NA, NA), c = c(7, 8, 9, 10, NA, 10), d = c(NA, 7, 8,
9, NA, 13), e = c(NA, 6L, 7L, 8L, 9L, 10L), f = c(NA, NA, NA,
4L, 5L, NA)), class = "data.frame", row.names = c(NA, -6L))