change value at specific location in a tibble

Viewed 40

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

2 Answers

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

You could maybe use the rows_update() function from dplyr?

rows_update(df, tibble(col1=2, col2=44))

# Matching, by = "col1"
# A tibble: 4 x 3
   col1  col2  col3
  <int> <int> <int>
1     1     5     9
2     2    44    10
3     3     7    11
4     4     8    12
Related