Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Can exists() function be used within mutate() (dplyr package)?

Tags:

r

dplyr

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.

like image 394
rdatasculptor Avatar asked Feb 02 '15 11:02

rdatasculptor


People also ask

What does mutate () do in R?

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.

What does dplyr package do in R?

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.

How do you mutate a new variable in R?

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.

What library is mutate in R?

mutate() is a rather simple method to use to manipulate datasets. This can be used to install the dplyr library.


1 Answers

You can use

mutate(df, var2 = if (exists('var2', where = df)) var2 else NA)
like image 186
Sven Hohenstein Avatar answered Oct 20 '22 00:10

Sven Hohenstein