三种替代解决方案:
1)使用data.table:
您可以使用与包中相同的melt
功能reshape2
(这是一个扩展和改进的实现)。melt
fromdata.table
也有比melt
-function from更多的参数reshape2
。例如,您还可以指定变量列的名称:
library(data.table)
long <- melt(setDT(wide), id.vars = c("Code","Country"), variable.name = "year")
这使:
> long
Code Country year value
1: AFG Afghanistan 1950 20,249
2: ALB Albania 1950 8,097
3: AFG Afghanistan 1951 21,352
4: ALB Albania 1951 8,986
5: AFG Afghanistan 1952 22,532
6: ALB Albania 1952 10,058
7: AFG Afghanistan 1953 23,557
8: ALB Albania 1953 11,123
9: AFG Afghanistan 1954 24,555
10: ALB Albania 1954 12,246
一些替代符号:
melt(setDT(wide), id.vars = 1:2, variable.name = "year")
melt(setDT(wide), measure.vars = 3:7, variable.name = "year")
melt(setDT(wide), measure.vars = as.character(1950:1954), variable.name = "year")
2)使用tidyr:
library(tidyr)
long <- wide %>% gather(year, value, -c(Code, Country))
一些替代符号:
wide %>% gather(year, value, -Code, -Country)
wide %>% gather(year, value, -1:-2)
wide %>% gather(year, value, -(1:2))
wide %>% gather(year, value, -1, -2)
wide %>% gather(year, value, 3:7)
wide %>% gather(year, value, `1950`:`1954`)
3) 使用reshape2:
library(reshape2)
long <- melt(wide, id.vars = c("Code", "Country"))
给出相同结果的一些替代符号:
# you can also define the id-variables by column number
melt(wide, id.vars = 1:2)
# as an alternative you can also specify the measure-variables
# all other variables will then be used as id-variables
melt(wide, measure.vars = 3:7)
melt(wide, measure.vars = as.character(1950:1954))
笔记:
- reshape2已退休。只有将其保留在 CRAN 上所需的更改才会进行。(来源)
- 如果要排除
NA
值,可以添加na.rm = TRUE
到函数中melt
。gather
数据的另一个问题是这些值将被 R 作为字符值读取(作为,
数字中的结果)。您可以使用gsub
和修复它as.numeric
:
long$value <- as.numeric(gsub(",", "", long$value))
或直接使用data.table
or dplyr
:
# data.table
long <- melt(setDT(wide),
id.vars = c("Code","Country"),
variable.name = "year")[, value := as.numeric(gsub(",", "", value))]
# tidyr and dplyr
long <- wide %>% gather(year, value, -c(Code,Country)) %>%
mutate(value = as.numeric(gsub(",", "", value)))
数据:
wide <- read.table(text="Code Country 1950 1951 1952 1953 1954
AFG Afghanistan 20,249 21,352 22,532 23,557 24,555
ALB Albania 8,097 8,986 10,058 11,123 12,246", header=TRUE, check.names=FALSE)