0

I have a list of tables:

a <- c(1:10)
b <- c(11:20)
c <- c(31:40)


df1 <- data.frame(a,b,c,id="A")
df2 <- data.frame(a,b,c,id="B")
df3 <- data.frame(a,b,c,id="C")

List1 <- list(df1,df2,df3)
List1

How can I select out a table from the list which has id=="C"

Thank you for your help.

adam.888
  • 7,686
  • 17
  • 70
  • 105

4 Answers4

3

You can name each data frame in the list using its value of id, then select C using normal list subsetting operations.

names(List1) <- sapply(List1, function(x) x[1, "id"])
List1[["C"]]
rsoren
  • 4,036
  • 3
  • 26
  • 37
2

One of many of ways to get this is with sapply in a list index [[.

> List1[[which(sapply(List1, function(x) levels(x$id)) == "C")]]
#     a  b  c id
# 1   1 11 31  C
# 2   2 12 32  C
# 3   3 13 33  C
# 4   4 14 34  C
# 5   5 15 35  C
# 6   6 16 36  C
# 7   7 17 37  C
# 8   8 18 38  C
# 9   9 19 39  C
# 10 10 20 40  C

Or with logical subsetting instead of which

> List1[sapply(List1, function(x) levels(x$id)) == "C"]
## or
> m <- mapply(function(x, y){ levels(x[[y]]) }, List1, "id") == "C"
> List1[m]
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
1

I am sure there is a one liner out there somewhere but I wrote a quick function below:

getsub <- function(x) {for(i in 1:length(x)){
  if(all(x[[i]]$id== "C")){
    return(x[[i]])
  } else {
    next
  }
}}

R> getsub(List1)
    a  b  c id
1   1 11 31  C
2   2 12 32  C
3   3 13 33  C
4   4 14 34  C
5   5 15 35  C
6   6 16 36  C
7   7 17 37  C
8   8 18 38  C
9   9 19 39  C
10 10 20 40  C
R> 
Stedy
  • 7,359
  • 14
  • 57
  • 77
0

Easy to understand function:

> getlist = function(mylist){
+ for(i in 1:length(mylist)) {ifelse(mylist[[i]]$id=='C', return(mylist[[i]]),"")}
+ }
> 
> 
> getlist(List1)
    a  b  c id
1   1 11 31  C
2   2 12 32  C
3   3 13 33  C
4   4 14 34  C
5   5 15 35  C
6   6 16 36  C
7   7 17 37  C
8   8 18 38  C
9   9 19 39  C
10 10 20 40  C
> 
rnso
  • 23,686
  • 25
  • 112
  • 234