I have a vector containing string representing names of variables that should be in my final df. Those names could change every time based on other conditions.
x <- colnames(df)
y <- c("blue", "yellow", "red")
z <- setdiff(y,x)
Let's say my result now is that: z = c("blue", "red")
I would like a function that, if
any element of vector y is missing from z, THEN
the function will create a column on df
with such element as variable name.
Here's my inconclusive attempt:
if (length(z) > 0) {
for (i in z) {
df$i <- NA
}
}
The part I don't know how to do is pass i
as an argument for creating a new variable on df
.
In my example: I should finally get df$yellow
as a new variable of df
.
I checked many posts, either I don't understand how it works, or they are not doing what I need, some for reference: