-1

I have a data frame like this one:

dat1 = data.frame("name" = c("Peter", "Tom", "Peter", "Peter", "Tom", "Tom"), "adress" = c("str1", "str2", "str1", "str2", "str3", "str3"), "product" = c("prod1", "prod1", "prod2", "prod3", "prod2", "prod2"), "val" = c(1,2,3,4,5,5))

Now I would like to create a new data frame which has columns "name", "adress" and all unique values of "product". The values in the columns of type "product" should be the sums of "val". Here´s the desired output:

result = data.frame("name" = c("Peter", "Tom", "Peter", "Tom"), "adress" = c("str1", "str2", "str2", "str3"), "prod1" = c(1,NA,NA,NA), "prod2" = c(3,NA,NA,10), "prod3" = c(NA,NA,4,NA))

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
WinterMensch
  • 643
  • 1
  • 7
  • 17

1 Answers1

-1

A possible solution with the package reshape2:

reshape2::dcast(dat1, name + adress ~ product, sum, value.var = "val")
J_F
  • 9,956
  • 2
  • 31
  • 55