三種可供選擇的解決方案:
1:隨着reshape2
library(reshape2)
long <- melt(wide, id.vars = c("Code", "Country"))
捐贈:
Code Country variable 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
一些替代符號,給相同的結果:
# 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:隨着data.table
可以使用相同melt
功能如reshape2
包(其是一個擴展&改進的實現)。 melt
from data.table
也有更多參數melt
from reshape2
。您可以的exaple還指定了可變列的名稱:
library(data.table)
long <- melt(setDT(wide), id.vars=c("Code","Country"), variable.name="year")
一些替代符號:
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")
3: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`)
如果你想排除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)
不知道如果是這樣的問題,但在重塑包的功能是熔體鑄造 – 2010-02-02 17:51:33
而重塑包已被取代reshape2。 – 2014-09-16 00:10:34
現在,reshape2已被tidyr取代。 – drhagen 2016-02-15 13:37:36