0

I'm working with a time-series tibble that is organized in the following way:

Country<- ('Somalia')
'1961'<- 2999
'1962'<- 2917
'1963'<- 1853
df <- data.frame(Country, `1961`, `1962`, `1963`)
df

The problem is that is extremely hard to work with data organized in such a way, since that the only way to access the data that I want (those numbers that are under the column names) is by referring to each year individually. Is there a simple way to organize them in a tidy way, such as:

x <- 'Somalia'
y <- c('1961', '1962', '1963')
z <- c(2999, 2917, 1853)
df <- data.frame(x, y, z)
df

Without having to manually rebuild the entire dataset?

John P. S.
  • 367
  • 3
  • 17

1 Answers1

0
> library(tidyverse)
> df %>% 
    gather(Year, Value, -Country)
  Country Year Value
1 Somalia 1961  2999
2 Somalia 1962  2917
3 Somalia 1963  1853

where df is

df <- data.frame(Country = "Somalia", 
             `1961` = 2999,
             `1962` = 2917,
             `1963` = 1853,
             check.names = FALSE)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138