简体   繁体   中英

R selecting a table from a list of tables by id

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.

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"]]

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]

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> 

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
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM