I'm importing data via an API. I do not know beforehand the list of variables that will get exported. How can I add a check to see if a variable exists? If it does, I want the values to remain the same. If it does not exist, I would like to create it and set to NA.
This is the code for replication:
# create dataframe
df <- data.frame(col1 = 5:8, col2 = 9:12)
# check if col3 exists in names (it doesn't), if it does keep the same values, if not set to NA
df$col3 <- ifelse("col3" %in% names(df) == TRUE, df$col3 <- df$col3, NA)
# same as above, but the variable col2 does exist
df$col2 <- ifelse("col2" %in% names(df) == TRUE, df$col2 <- df$col2, NA)
Setting the values of the variable to NA when it does not exist works well. However, when the variable exists, I get a column of length 4 with the first value ("9") repeated and I want a column with 9:12.