简体   繁体   中英

R-How to split list of row value into new column value against ID

I'm new to r programming, i need to achieve below desire output can you please help me. dataframe:

ID      Name                      
 1      null                      
 2      list(A = 10, B = 20)      
 2      list(G = 4, U = 2)        
 3      null                      
 3      null                      
 4      list(A = 7, B = 10)

Desired Output will be,

ID      Measure                   Measure.A   Measure.B                 
 1      null                      null          null                   
 2      list(A = 10, B = 20)      10             20                    
 2      list(A = 4, B = 2)         4              2                     
 3      null                       null          null                  
 3      null                       null          null                  
 4      list(A = 7, B = 10)        7              10                   

It is better to have NA instead of NULL elements in a data.frame . Loop through the 'Name' column (assuming it is a list with nested list elements), replace the NULL (assuming it is real NULL and not a character string "null" ) with NA and rbind the elements using do.call . Assign the output to create two new columns in 'df1'

df1[c("Measure.A", "Measure.B")] <- unlist(do.call(rbind, 
            lapply(df1$Name, function(x) replace(x, is.null(x), NA))))

names(df1)[2] <- "Measure"  

data

df1 <- structure(list(ID = c(1, 2, 2, 3, 3, 4), Name = structure(list(
NULL, structure(list(A = 10, B = 20), .Names = c("A", "B"
)), structure(list(G = 4, U = 2), .Names = c("G", "U")), 
NULL, NULL, structure(list(A = 7, B = 10), .Names = c("A", 
"B"))), class = "AsIs")), .Names = c("ID", "Name"), row.names = c(NA, 
-6L), class = "data.frame")

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