Search code examples
rdataframesapply

Store output of sapply into a data frame?


how can I store the output of sapply() to a dataframe where the index value is stored in first column and its value in corresponding 2nd column. For illustration, I have shown only 2 elements here, but there are 110 columns in my data. "loan" is the data frame.

cols <- sapply(loan,function(x) sum(is.na(x)))                                                          
cols                                                                          
id                                                                               
0                                                                              
member_id                                                                             
7

I want output as:

var         value                             
id            0                                  
member_id     7   

I know that sapply() returns a vector, but when I print the vector, values are printed along with its some "index" e.g., column name if applied on a data frame. So, now when I want to store it as a data frame with two columns where 1st column contains the index part and the second column contains the value, how can I do it?


Solution

  • I found an answer to my question. For those who actually did understand my problem, this answer might make sense:

    cols <- data.frame(sapply(loan ,function(x) sum(is.na(x))))                     
    
    cols <- cbind(variable = row.names(cols), cols)
    

    I wanted the row.names to be in a column of the same data frame corresponding to the values obtained from sapply.