How do I convert/reshape a data frame in long format to a wide format without aggregating the records?
From this:
> test <- data.frame(x = c("a","a","a"), y = c("b","b","c"), z = c(1,2,1))
> te开发者_StackOverflow中文版st
x y z
1 a b 1
2 a b 2
3 a c 1
To this:
x b c
1 a 1 NA
2 a 2 NA
3 a NA 1
Since the x
column in the test
data-frame doesn't uniquely identify the rows, and yet you don't want to do any aggregation, you need to augment the data-frame with a unique id
column, and then use dcast()
from the reshape2
package:
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
精彩评论