三种替代解决方案:
1)与 数据表:
您可以使用与包中相同的melt
功能reshape2
(这是扩展和改进的实现)。melt
from data.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)与 提迪尔:
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)与 重塑2:
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))
笔记:
- 重塑2退休了。仅进行必要的更改以将其保留在CRAN上。(来源)
- 如果要排除
NA
值,则可以将和功能添加na.rm = TRUE
到。melt
gather
数据的另一个问题是R会将这些值读取为字符值(作为数字中的结果,
)。您可以使用gsub
和进行修复as.numeric
:
long$value <- as.numeric(gsub(",", "", long$value))
或直接使用data.table
或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)