1

The data I have is in the below format:-

dataFrame_before

I would like to group by name and have each of the keys as a column with values as fields in it.

After which it would look like

dataFrame_after

The code to create these dataframes :-

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")) 
asarapure
  • 605
  • 1
  • 6
  • 18

2 Answers2

2

This is one line with tidyr:

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

"key" and "value" are arguments in spread.

Willie D
  • 145
  • 1
  • 10
1

Reshape2 package in R should help you.

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')] 
amrrs
  • 6,215
  • 2
  • 18
  • 27