Stephen Poole
Stephen Poole

Reputation: 381

How can I update these rows that match a condition in another column of my data frame?

I'm trying to update Sam's role in the tibble below from PM to TC. For some reason, I have no idea how to get this to work, even though it seems simple. Here is my data frame.

df <- tibble(
          Name = c("Sam","Jane","Sam","Sam","James","Mary","Swain"),
          Role = c("PM","TC","PM","PM","RX","TC","TC"),
          Number = c(1:7)
          
        )
    

Then I have this if_else statement which is supposed to conditionally update Role to "TC" when Name = "Sam." But all it's doing is changing all the row values to TC regardless of name. I don't know why or how to fix it.

df$Role <- if_else(df$Name == "Sam", df$Role <-  "TC", df$Role) 

Upvotes: 2

Views: 1127

Answers (1)

Anoushiravan R
Anoushiravan R

Reputation: 21908

You could also use mutate function and refer to column names without dollar sign and data frame name as if they are like any objects in R:

library(dplyr)

df %>%
  mutate(Role = if_else(Name == 'Sam', 'TC', Role))

# A tibble: 7 × 3
  Name  Role  Number
  <chr> <chr>  <int>
1 Sam   TC         1
2 Jane  TC         2
3 Sam   TC         3
4 Sam   TC         4
5 James RX         5
6 Mary  TC         6
7 Swain TC         7

Upvotes: 4

Related Questions