Home > other >  Is there an easy way to extend a single column in an R dataframe?
Is there an easy way to extend a single column in an R dataframe?

Time:02-24

I want to extend my dataset with missing observations in order to compute forecasts. This means I want to extend my 'time' column and set all the new cells from the other columns to NA:

Time1 <- c(2019, 2020, 2021, 2022)
data1 <- c(3, 4, 1, 4)
df1 <- cbind(Time1, data1)

Time2 <- c(2019, 2020, 2021, 2022, 2023, 2024, 2025)
data2 <- c(3, 4, 1, 4, NA, NA, NA)
df2 <- cbind(Time2, data2)

Is there an easy way to get from df1 to df2 without creating a new dataframe?

CodePudding user response:

You can do it like this:

library(dplyr)


df1 <- as_tibble(df1)
df1 %>% add_row(Time1 = seq(from =2023, to = 2025, by = 1))
  •  Tags:  
  • r
  • Related