How to convert / change data frame in long format to wide format without aggregating records?

From this:

> test <- data.frame(x = c("a","a","a"), y = c("b","b","c"), z = c(1,2,1))
> test
  x y z
1 a b 1
2 a b 2
3 a c 1

For this:

  x b c
1 a 1 NA
2 a 2 NA
3 a NA 1
+3
source share
1 answer

Since the column xin the data frame testdoes not uniquely identify the rows, and yet you do not want to do any aggregations, you need to enlarge the data frame using a unique one id, and then use dcast()from the package reshape2:

require(reshape2)
test$id <- 1:nrow(test)


> dcast(test, id + x ~ y, value_var = 'z')[,-1]
  x  b  c
1 a  1 NA
2 a  2 NA
3 a NA  1
+5
source

All Articles