view raw
asarapure asarapure - 9 months ago 54
R Question

Converting fields of a column into separate columns

The data I have is in the below format:-


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


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


This is one line with tidyr:

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

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