Luca
Luca

Reputation: 107

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?

Upvotes: 2

Views: 179

Answers (1)

akrun
akrun

Reputation: 887173

We create an index ('i1') based on the occurence of '2' in 'Name' column, using that index, subset the 'Side' and change the values with chartr

i1 <- grep("2", df$Name)
df$Side[i1] <- chartr("LR", "RL", df$Side[i1])
df
#   Name Side
#1  a2b    R
#2  a1a    R
#3  b2a    L
#4  a2b    R
#5  b1b    R
#6  b2a    R

Or another option is to assign using levels as the 'Side' column is factor

levels(df$Side[i1]) <- rev(levels(df$Side[i1]))

Upvotes: 4

Related Questions