[英]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.我还有另外两个向量,一个是在创建 data.frame 时可以回收的字符向量,另一个是 integer 向量。
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.这些日期列可能是空的,因为我正在使用 for 循环来填充表格。
How can I add all dates defined in the sequence as columns to the data.frame/data.table, so that...如何将序列中定义的所有日期作为列添加到 data.frame/data.table,以便...
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
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然后通过将它们绑定到您的data.frame
newdf <- cbind(df,toAdd)
We can also do this with expand.grid
我们也可以用expand.grid
做到这一点
out <- expand.grid(ID.vec, type.vec)
out[new_cols] <- NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.