dimanche 9 juillet 2017

Change value in a 2-value column to its opposite only if a condition in another column is met

I am having problems with some strings I have to change in my data frame. My df is structured like this:

df <- data.frame(Name = c("a2b", "a1a", "b2a", "a2b", "b1b", "b2a"),
                 Side = c("L", "R", "R", "L", "R", "L"))

    Name    Side
1    a2b       L
2    a1a       R
3    b2a       R
4    a2b       L
5    b1b       R
6    b2a       L

What I want to do is replace the value in the "Side" column with its opposite only when the "Name" value has a "2" in it (leaving the rows where the value has "1" unchanged). The "Side" column only has "R" and "L" as possible values. So this is the output that I would like to get:

    Name    Side
1    a2b       R
2    a1a       R
3    b2a       L
4    a2b       R
5    b1b       R
6    b2a       R

I tried many solutions but I am just starting to work with R so I don't really know how "if" statements work yet. Is there a way to do it?

Aucun commentaire:

Enregistrer un commentaire