这个问题的基本 R reshape 方法非常难看,特别是因为名称不是reshape 喜欢的形式。如下所示,第一行 setNames 将列名修改为 reshape 可以使用的名称。
reshape(
setNames(mydf, c("Country", paste0("val.", c(2001, 2002, 2003)))),
direction = "long", idvar = "Country", varying = 2:ncol(mydf),
sep = ".", new.row.names = seq_len(prod(dim(mydf[-1]))))
base R 中更好的替代方法是使用stack,如下所示:
cbind(mydf[1], stack(mydf[-1]))
# Country values ind
# 1 Nigeria 1 2001
# 2 UK 2 2001
# 3 Nigeria 2 2002
# 4 UK NA 2002
# 5 Nigeria 3 2003
# 6 UK 1 2003
现在还有用于重塑数据的新工具,例如“tidyr”包,它为我们提供了gather。当然,tidyr:::gather_.data.frame 方法只是调用了reshape2::melt,所以我的这部分答案除了介绍您可能在 Hadleyverse 中遇到的新语法之外,不一定要添加太多内容。
library(tidyr)
gather(mydf, year, value, `2001`:`2003`) ## Note the backticks
# Country year value
# 1 Nigeria 2001 1
# 2 UK 2001 2
# 3 Nigeria 2002 2
# 4 UK 2002 NA
# 5 Nigeria 2003 3
# 6 UK 2003 1
如果您想要问题中显示的行顺序,则此处的所有三个选项都需要对行进行重新排序。
第四个选项是使用我的“splitstackshape”包中的merged.stack。与基本 R 的 reshape 一样,您需要将列名修改为包含“变量”和“时间”指示符的名称。
library(splitstackshape)
merged.stack(
setNames(mydf, c("Country", paste0("V.", 2001:2003))),
var.stubs = "V", sep = ".")
# Country .time_1 V
# 1: Nigeria 2001 1
# 2: Nigeria 2002 2
# 3: Nigeria 2003 3
# 4: UK 2001 2
# 5: UK 2002 NA
# 6: UK 2003 1
样本数据
mydf <- structure(list(Country = c("Nigeria", "UK"), `2001` = 1:2, `2002` = c(2L,
NA), `2003` = c(3L, 1L)), .Names = c("Country", "2001", "2002",
"2003"), row.names = 1:2, class = "data.frame")