vendredi 28 juin 2019

Creating a new variable in r using ifelse and %in%

I want to create a new variable where if the variable $Who.went.first is contained within the variable $Who.should.go.first then it will return TRUE for the new variable, else it returns FALSE. $Who.should.go.first and $Who.went.first both have the same set of car names as input, except for some reason all the $Who.should.go.first inputs have the text "(Aspect)" at the end, hence I want the function to check $Who.went.first is contained within $Who.went.first rather than looking for exact matches.

I'm trying to do this using the ifelse function and %in%, as shown below.

Cooperation_2clean$correct.go.first <- ifelse((Cooperation_2clean$Who.went.first %in% Cooperation_2clean$Who.should.go.first), "TRUE", "FALSE")

It will create a new variable, except every case returns FALSE. For example, if $Who.went.first is "AV_0_Blue" and $Who.should.go.first is "AV_0_Blue (Aspect)" then it returns FALSE when it should be true.

Should I be using a different function such as case_when?

Aucun commentaire:

Enregistrer un commentaire