I want to make a new variable in case it doesn't exist. If it exists nothing has to be changed, but if it doesn't I want to make this variable and give it NA values. I tried to do this with mutate function of the dplyr package, but I only get NA's as a result.
library(dplyr)
df <- structure(list(var1 = c(47, 801, 660), var2 = c(11,
17, 11)), .Names = c("var1", "var2"), row.names = c(NA,
3L), class = "data.frame")
Now I check the existence of var2.
df <- mutate(df, var2 = ifelse(exists('var2')==TRUE,var2,NA))
the result is:
var1 var2
1 47 NA
2 801 NA
3 660 NA
but, the result SHOULD be (because nothing had to be changed:
var1 var2
1 47 11
2 801 17
3 660 11
Does anyone know how to solve this problem? Can it even be done with exists()? Many thanks in advance.
In R programming, the mutate function is used to create a new variable from a data set. In order to use the function, we need to install the dplyr package, which is an add-on to R that includes a host of cool functions for selecting, filtering, grouping, and arranging data.
dplyr is a new package which provides a set of tools for efficiently manipulating datasets in R. dplyr is the next iteration of plyr , focussing on only data frames. dplyr is faster, has a more consistent API and should be easier to use.
To use mutate in R, all you need to do is call the function, specify the dataframe, and specify the name-value pair for the new variable you want to create.
mutate() is a rather simple method to use to manipulate datasets. This can be used to install the dplyr library.
You can use
mutate(df, var2 = if (exists('var2', where = df)) var2 else NA)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With