Search code examples
rvariablesdplyr

Change value in tibble column element in R


I have a dataset :

library(tidyverse)
fac = factor(c("a","b","c"))
x = c(1,2,3)
d = tibble(fac,x);d

that looks like this :

# A tibble: 3 × 2
  fac       x
  <fct> <dbl>
1 a         1
2 b         2
3 c         3

I want to change the value 2 of column x that corresponds to factor b with 3.14.

How can I do it in the dplyr pipeline framework ?


Solution

  • We may use replace

    library(dplyr)
    library(magrittr)
    d %<>% 
       mutate(x = replace(x, fac == "b", 3.14))
    

    -output

    d
    # A tibble: 3 × 2
      fac       x
      <fct> <dbl>
    1 a      1   
    2 b      3.14
    3 c      3