如何在不聚合记录的情况下将长格式数据帧转换/重新整形为宽格式?

时间:2022-03-30 04:28:00

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

To this:

对此:

  x b c
1 a 1 NA
2 a 2 NA
3 a NA 1

1 个解决方案

#1


5  

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:

由于测试数据框中的x列不能唯一标识行,但您不想进行任何聚合,因此需要使用唯一的id列扩充数据框,然后使用dcast()来自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

#1


5  

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:

由于测试数据框中的x列不能唯一标识行,但您不想进行任何聚合,因此需要使用唯一的id列扩充数据框,然后使用dcast()来自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