在R中转换数据帧的简单方法 - 将一个变量值转换为单独的列

时间:2016-01-28 11:52:15

标签: r dataframe

我所拥有的(显然我只提供了当前数据的一小部分):

my_df <- structure(list(X = structure(c(48.75, 49.25), .Dim = 2L), Y = structure(c(17.25, 17.25), .Dim = 2L), Time = structure(c(14625, 14626), .Dim = 2L, class = "Date"), spei = c(-0.460236400365829, -0.625695407390594)), .Names = c("X", "Y", "Time", "spei"), row.names = 1:2, class = "data.frame")

我需要什么:

new_df <- structure(list(X = structure(c(48.75, 49.25), .Dim = 2L), Y = structure(c(17.25, 17.25), .Dim = 2L), "2010-01-16" = c(-0.460236400365829, NaN), "2010-01-17" = c(NaN, -0.625695407390594)), .Names = c("X", "Y", "2010-01-16", "2010-01-17"), row.names = 1:2, class = "data.frame")

最简单的方法是什么? 我想过写一个for循环,但是我觉得应用/ sapply可能对此有帮助吗?

transformation needed

2 个答案:

答案 0 :(得分:2)

您可以使用库tidyr及其spread功能,如下所示:

library(tidyr)
spread(my_df, Time, spei)
      X     Y 2010-01-16 2010-01-17
1 48.75 17.25 -0.4602364         NA
2 49.25 17.25         NA -0.6256954

答案 1 :(得分:2)

如果没有任何其他套餐,您可以使用reshape()

执行此操作
reshape(my_df, idvar = c('X', 'Y'), timevar = "Time", direction = 'wide')

给出了:

      X     Y spei.2010-01-16 spei.2010-01-17
1 48.75 17.25      -0.4602364              NA
2 49.25 17.25              NA      -0.6256954