I have a dataframe and a string.
I need to check if the elements in the string are in the colnames of the dataframe.
If not in the dataframe, I need to create a new column,
If they are in the dataframe, do nothing
Here is my reprex:
# dataframe
df <- data.frame(name = c("jon", "dan", "jim"),
age = c(44, 33, 33))
# string
st <- c("house", "car", "pet")
# for just one element in the string, this works
df %>%
mutate(house = if (exists('house', where = .)) house else "not there")
however, my function to apply to multiple elements is not working.. any help much appreciated..
make_missing_cols <- function(df, cols){
for(i in cols) {
df <- df %>%
mutate(cols[i] = if(exists(cols[i], where = df)) cols[i] else "not there")
}
return(df)
}