asarapure asarapure - 3 months ago 24
R Question

Converting fields of a column into separate columns

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

Answer

This is one line with tidyr:

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

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