0

I have an existing R dataframe that is filled out. I want to enter in new information in a series of new columns. If I have a list of the column names, is there an easy way to form all these empty columns?

I will then fill out the entries based on outputs of later calculations

MWE

animal = c("echidna", "kangaroo", "emu")
age = c(3, 7, 4)
df <- data.frame(animal, age)

newColumns = c("pen", "colour", "sex")

I know I can do

df$pen = NA
df$colour = NA
df$sex = NA

but since I have the list, and it's long - is there an efficient way to do this?

Esme_
  • 1,360
  • 3
  • 18
  • 30
  • 1
    `df[newColumns] <- NA` – Ronak Shah Nov 05 '20 at 05:04
  • Is there a reason you want to pre-add them? Are you filling them later? Can you not just assign them once you've created them? – MrFlick Nov 05 '20 at 05:08
  • @MrFlick I just find it easier to set up the structure of the df and then fill in the individual cells as I calculate them. If I create them all in one go I can then just update each individual cell as required. I don't know if this is a good or bad way to do it, but from an understanding my code perspective it makes things easier for me. – Esme_ Nov 05 '20 at 05:25

0 Answers0