Search code examples
rtidyverse

change value at specific location in a tibble


I have a df

df = data.frame(col1=1:4, col2 = 5:8, col3 = 9:12)

I want to change the value in row2, col2 to 44

In base R, I use df["2","col2"] = 44, how do I do this in tidyverse?

df = data.frame(col1=1:4, col2 = 5:8, col3 = 9:12)
df
df["2","col2"]=44
df

enter image description here


Solution

  • A possible solution:

    library(dplyr)
    
    df %>% 
      mutate(col2 = ifelse(row_number() == 2, 44, col2))
    
    #>   col1 col2 col3
    #> 1    1    5    9
    #> 2    2   44   10
    #> 3    3    7   11
    #> 4    4    8   12