简体   繁体   中英

How can I design an r function that selects specific elements from a list of lists, and returns a dataframe as an output

I'm trying to set up an r function that will select relevant elements from a list, and end up with a dataframe as output.

Here is the list I'm using:

test_list<-list(set1=list(2, NA, NA, 8, NA, NA, 2), set2=list(4, 6, NA, NA, 2, 1, 1), set3=c(2, 3, 2, 1, NA, NA, NA))

For each element of my list, I'd like to keep only the sublists that contains less than 4 NA elements.

Here is the function I've built:

is.useful <-function(x){ #x is a list of sublists 
#I want to keep only the sublists with less than 4 NA elements
    vector <-c()
    for(i in x){
        if(sum(is.na(x[[i]])) <= 3){
        vector <-c(vector, unlist(x[[i]]))
        }
        }
    return (vector)
    }

Runing is.useful(test_list) , I'm getting the Error in x[[i]] : type 'list'

I don't understand the issue here because: sum(is.na(test_list[["set1"]])) returns the right answer 4 and unlist(test_list[["set1"]]) also gives me the sublist as a vector ( is.vector(unlist(test_list[["set1"]])) returns TRUE )

I've also tried something else, namely transforming the list of lists into a dataframe, using following command:

dd  <-  as.data.frame(matrix(unlist(test_list), nrow=length(unlist(test_list[1])))) 

From there, I try to run a very similar function, without the unlist:

is.useful2 <-function(x){ #x is dataframe
#I want to keep only the vectors with less than 4 NA elements
    vector <-c()
    for(i in x){
        if(sum(is.na(x[i])) <= 3){
        vector <-c(vector, (x[i]))
        }
        }
    return (vector)
    }

is.useful2(dd) returns Error in [.data.frame (x, i) : undefined columns selected

What do I expect? In this specific example, I expect a dataframe of 2 vectors, set2 and set3, for which I have less than 4 NA values.

I'm a bit lost. What did I do wrong ?

Thanks a lot for your help.

hope this helps:

 do.call(cbind,test_list[sapply(test_list,function(x)sum(is.na(unlist(x))))<4])
     set2 set3
[1,] 4    2   
[2,] 6    3   
[3,] NA   2   
[4,] NA   1   
[5,] 2    NA  
[6,] 1    NA  
[7,] 1    NA  

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