creating new variable using mutate() - no applicable method for 'mutate_' applied to an object of class "character"

Dear R Studio Community,

I've currently been working with a data set like this:

df <- data.frame(var1 <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4), var2 <- c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4))

I've been trying to create a new variable using mutate() and if_else(). The idea is that the new variable gets assigned to the two existing variables var1 and var2 by different value combinations, meaning:

var3 = 1 IF var1 = 1 and var2 = 2 OR var1 = 3 and var2 = 4
var3 = 2 IF var1 = 1 and var2 = 3 OR var1 = 2 and var2 = 4

The other combinations are not of importance and can result in "NA"

I've been trying to create the new variable like this:

df$var3 <- mutate(var3 = if_else(df$var1 == 1 && df$var2 == 2 | df$var1 == 3 && df$var2 == 4), "1", if_else(df$var1 == 1 && df$var2 == 3 | df$var1 == 2 && df$var2 == 4 ), "2")

But the problem "no applicable method for 'mutate_' applied to an object of class "character"" keeps popping up.

I'm still quite new to R so I'm not really sure where this issue is coming from and whether my method even makes sense to begin with. I hope that you understand my idea behind all this and can help me with this issue!

Try the code below. The changes I made are:
Use = not <- to assign column in data.frame()
The first argument of mutate is the data frame it is acting on.
Use &, not &&, in ifelse
When the ifelse is inside of mutate, you can refer to column by the bare names like var1 and you do not need to use references like df$var1.
Your parentheses structure was wrong in the nested ifelse.

There is a case_when function in dplyr that is inteded to avoid nested ifelse functions. That would be worth looking at.

library(dplyr)
df <- data.frame(var1 = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4), 
                 var2 = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4))

df <- mutate(df, var3 = if_else(var1 == 1 & var2 == 2 | var1 == 3 & var2 == 4, "1", 
                                 if_else(var1 == 1 & var2 == 3 | var1 == 2 & var2 == 4 , "2", "NA")))

This worked perfectly! Thank you for the super quick response :hibiscus:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.