Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In R, how to give a vector of strings to make into empty columns?

If I have a vector of strings, how can I easily make them into column headers appended onto a dataframe? I know I could use cbind one-by-one, but is there a way to do it in one pass?

library(dplyr)
my_new_cols <- c("n_a", "n_b", "n_c")

current_data <- tibble(id = c(1:4),
                       score = c(10, 20, 30, 40))

desired_output <- tibble(id = c(1:4),
                       score = c(10, 20, 30, 40),
                       n_a = NA,
                       n_b = NA,
                       n_c = NA)
~~~~~

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One simple way:

current_data[my_new_cols] <- NA

This syntax refers to the three new columns you want to add, creating them in the process, and assigning NA for all column values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading