Home > Mobile >  Change value in tibble column element in R
Change value in tibble column element in R

Time:03-06

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 ?

CodePudding user response:

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   

CodePudding user response:

One alternative with ifelse statement:

library(dplyr)

d %>% 
  mutate(x = ifelse(fac == "b", 3.14, x))
  fac       x
  <fct> <dbl>
1 a      1   
2 b      3.14
3 c      3 
  • Related