Two alternative solutions:
1) With data.table:
You can use the melt
function:
library(data.table)
long <- melt(setDT(wide), id.vars = c("Code","Country"), variable.name = "year")
which gives:
> 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
Some alternative notations:
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) With tidyr:
Use pivot_longer()
:
library(tidyr)
long <- wide %>%
pivot_longer(
cols = `1950`:`1954`,
names_to = "year",
values_to = "value"
)
Note:
names_to
and values_to
default to "name"
and "value"
, respectively, so you could write this extra-succinctly as wide %>% pivot_longer(`1950`:`1954`)
.
- The
cols
argument uses the highly flexible tidyselect DSL, so you can select the same columns using a negative selection (!c(Code, Country)
), a selection helper(starts_with("19")
; matches("^\\d{4}$")
), numeric indices (3:7
), and more.
tidyr::pivot_longer()
is the successor to tidyr::gather()
and reshape2::melt()
, which are no longer under development.
Transforming values
Another problem with the data is that the values will be read by R as character-values (as a result of the ,
in the numbers). You can repair with gsub
and as.numeric
, either before reshaping:
long$value <- as.numeric(gsub(",", "", long$value))
Or during reshaping, with data.table
or tidyr
:
# data.table
long <- melt(setDT(wide),
id.vars = c("Code","Country"),
variable.name = "year")[, value := as.numeric(gsub(",", "", value))]
# tidyr
long <- wide %>%
pivot_longer(
cols = `1950`:`1954`,
names_to = "year",
values_to = "value",
values_transform = ~ as.numeric(gsub(",", "", .x))
)
Data:
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)
tidyr
'sgather
andspread
have been replaced bypivot_*
functions. – Statued