Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

r - How to add multiple empty columns to an empty data frame?

I have created an empty data frame empty_df, and want to add new columns of type double() with names new_col_names, to get target_df (empty data frame with old columns and new columns)

Clarification: The type does not matter, could also just be an empty colmn without a specified type if that is possible. I will assign some numeric vectors to those columns later on.

new_col_names <- c("A", "B", "C")

empty_df <- data.frame(col1 = as.Date(character()),
                       col2 = integer(),
                       col3 = double())

target_df <- data.frame(col1 = as.Date(character()),
                       col2 = integer(),
                       col3 = double(),
                       A = double(),
                       B = double(),
                       C = double())

How is this possible?

question from:https://stackoverflow.com/questions/66062388/how-to-add-multiple-empty-columns-to-an-empty-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can run a for loop

library(tidyverse)

new_col_names <- c("A", "B", "C")

empty_df <- data.frame(col1 = as.Date(character()),
                       col2 = integer(),
                       col3 = double())



for (names in new_col_names){
   empty_df[,names] <- double()
}

empty_df
#> [1] col1 col2 col3 A    B    C   
#> <0 rows> (or 0-length row.names)

Created on 2021-02-05 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...