AlexWithYou
AlexWithYou

Reputation: 429

Read values in dataframe and store it in a vector

I have a dataframe like this

  X  2001,2002,2003
 JAN   NA,1,2
 JUN   NA,2,3
 DEC   1,2,NA

I want an empty vector to store values and generate a time series What can I do

Intended output formated by month and year, omit NAs

 output=c(1,1,2,2,2,3)

How can I do?

Upvotes: 0

Views: 31

Answers (1)

m_ky
m_ky

Reputation: 51

You might go that direction:

library(tidyverse)

dta <- tribble(
  ~X,    ~"2001", ~"2002", ~"2003",
  "JAN", NA,      1,       2,
  "JUN", NA,      2,       3,
  "DEC", 1,       2,       NA)

dta %>%
  pivot_longer(cols = '2001':'2003', 
               names_to = "year", 
               values_to = "val") %>%
  arrange(year) %>%
  filter(!is.na(val))

However, you need to assure that the months are sorted correctly.

Upvotes: 1

Related Questions