R-如何根据ID

时间:2017-08-23 06:33:04

标签: r

我是r编程新手,我需要达到以下欲望输出,请你帮帮我。 数据帧:

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)

所需的输出将是,

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                   

1 个答案:

答案 0 :(得分:0)

最好在NULL中使用NA代替data.frame元素。循环通过名称'列(假设它是具有嵌套list元素的list),replace NULL(假设它是真正的NULL而不是字符串"null") NA和rbind使用do.call的元素。分配输出以在' 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"  

数据

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