Homer Jay Simpson
Homer Jay Simpson

Reputation: 1280

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 ?

Upvotes: 1

Views: 1411

Answers (2)

TarJae
TarJae

Reputation: 78927

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 

Upvotes: 4

akrun
akrun

Reputation: 887148

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   

Upvotes: 2

Related Questions