asarapure asarapure - 1 year ago 100
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"))

Answer Source

This is one line with tidyr:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download