aimbotter21
aimbotter21

Reputation: 331

R - How can I add columns to a data frame / data.table based on values of a vector that contains a sequence of dates

I have a vector of dates

 start_date    <- as.Date("1990-01-01", "%Y-%m-%d")
 end_date      <- as.Date("2021-01-31", "%Y-%m-%d")

 new_cols      <- seq(from = start_date, 
                    to = end_date,
                    by = "month")
 new_cols      <- as.yearmon(new_col, frac = 1)
 new_col_names <- as.character(new_cols)

I have two other vectors one character vector that can be recycled when creating the data.frame and one integer vector.

ID.vec <- c(1:100)
type.vec <- c("A", "B", "C")

data.frame( rep(ID.vec, each = 3), type.vec, ?? )

Those date columns could be empty for all I care, as I am using a for loop to populate the table.

How can I add all dates defined in the sequence as columns to the data.frame/data.table, so that...

ID     TYPE    2000-03-31  2000-04-30  2000-05-31  2000-06-30 etc
1      A       sth         sth         sth         sth
1      B       sth         sth         sth         sth
1      C       sth         sth         sth         sth
2      A       sth         sth         sth         sth
2      B       sth         sth         sth         sth
2      C       sth         sth         sth         sth
3      A       sth         sth         sth         sth
3      B       sth         sth         sth         sth
3      C       sth         sth         sth         sth

Upvotes: 0

Views: 31

Answers (2)

akrun
akrun

Reputation: 887691

We can also do this with expand.grid

out <- expand.grid(ID.vec, type.vec)
out[new_cols] <- NA

Upvotes: 0

Jonas
Jonas

Reputation: 1810

You can create the columns to add as folows

df <- data.frame(rep(ID.vec, each = 3), type.vec)

someInitialValue <- 0
toAdd <- setNames(data.frame(matrix(rep(someInitialValue,NROW(df)*length(new_col_names)), 
                                    ncol = length(new_col_names), 
                                    nrow = NROW(df))), 
                  new_col_names)

and then bind them to your data.frame via

newdf <- cbind(df,toAdd)

Upvotes: 1

Related Questions