Reputation: 4229
How to subset list of dataframes based on condition? This is possible duplicate, but I could not find it on SO!
Sample data:
data1 <- data.frame(ID=c(1,1),Name1=c(3,2),Name2=c(4,5),Name3=c(6,7),Name4=c(8,9))
data2 <- data.frame(ID=c(2,2),Name4=c(7,3),Name2=c(3,1),Name3=c(2,2),Name1=c(1,1))
data3 <- data.frame(ID=c(3),Name3=c(6),Name1=c(2),Name4=c(3),Name2=c(2))
data4 <- data.frame(ID=c(4,4),Name2=c(5,7),Name3=c(1,1),Name1=c(9,1),Name4=c(3,3))
listData <- list(data1,data2,data3,data4)
Normally with data.frame it would be just:
df <- data.frame(do.call(rbind, listData))
df[df$ID==3,]
So that I would get only the row where ID number is 3. How to subset in a list? Thanks.
EDIT: The desired output would be just the single entry (list) something like:
[[3]]
ID Name3 Name1 Name4 Name2
1 3 6 2 3 2
or just a row (data.frame):
ID Name3 Name1 Name4 Name2
1 3 6 2 3 2
Upvotes: 1
Views: 456
Reputation: 887901
Also:
listData[mapply(function(x,y) any(x==y),sapply(listData,`[`,1),3)]
#[[1]]
# ID Name3 Name1 Name4 Name2
#1 3 6 2 3 2
Upvotes: 1
Reputation: 193687
Maybe something like this can be used if you want to retain the values in a list:
names(listData) <- seq_along(listData) ## So we can identify which list item it came from
Subs <- lapply(listData, function(x) { y <- x[x$ID == 3, ]; if (nrow(y) == 0) NULL else y })
Subs[!sapply(Subs, is.null)]
$`3`
ID Name3 Name1 Name4 Name2
1 3 6 2 3 2
Upvotes: 3