将列的字段转换为单独的列

时间:2016-08-11 19:52:25

标签: r

我的数据格式如下: -

dataFrame_before

我想按名称分组,并将每个键作为列,其值为字段。

之后它看起来像

dataFrame_after

创建这些数据框的代码: -

df <- data.frame(company_id = c(12,12,12, 12, 12), 
             name1 = c("John", "Jack", "Joey", "Jack", "Joey"), 
             key = c("Phone_no", "address", "id" , "Phone_no", "address"), 
             value = c("32453", "street a", "007" , "78632", "street x"))

    expecteddf <- data.frame(company_id = c(12, 12,12 ), 
                     name1 = c("John", "Jack", "Joey"), 
                     Phone_no = c("32453", "78632",  "-"), 
                     address = c("-", "street a", "street x"),
                     id = c("-", "-", "007")) 

2 个答案:

答案 0 :(得分:2)

这是与tidyr的一行:

 require(tidyr)
 df = spread(df, key = key, value = value)

&#34;键&#34;和&#34;价值&#34;是传播的论据。

答案 1 :(得分:1)

R中的Reshape2包应该可以帮到你。

library(reshape2) #load the package
newdf <- dcast(df, company_id + name1  ~key) 

newdf[is.na(newdf)] <- '-' #replacing NAs with -

#sorting name1 and columns in the desired o/p format

newdf <- newdf[order(newdf$name1),c('company_id','name1','Phone_no','address','id')]