I want to replace apple
with frui
and pear
with bord
df <- tibble(
word = c("apple", "apple","apple","banana", "pear","pear"),
i = seq_along(word)
)
Any idea?
CodePudding user response:
A tidyverse option using str_replace_all
.
library(tidyverse)
mutate(df, word = str_replace_all(word, c('apple' = 'frui', 'pear' = 'bord')))
# # A tibble: 6 x 2
# word i
# <chr> <int>
# 1 frui 1
# 2 frui 2
# 3 frui 3
# 4 banana 4
# 5 bord 5
# 6 bord 6
CodePudding user response:
We could use recode
library(dplyr)
df <- df %>%
mutate(word = recode(word, apple = 'frui', pear = 'bord'))
-output
df
# A tibble: 6 × 2
word i
<chr> <int>
1 frui 1
2 frui 2
3 frui 3
4 banana 4
5 bord 5
6 bord 6
CodePudding user response:
For the sake of completeness, here is another tidyverse option using case_when
.
library(tidyverse)
df <- tibble(
word = c("apple", "apple","apple","banana", "pear","pear"),
i = seq_along(word)
)
df %>%
mutate(word = case_when(
TRUE ~ word,
word == "apple" ~ "frui",
word == "pear" ~ "bord"
))
#> # A tibble: 6 x 2
#> word i
#> <chr> <int>
#> 1 apple 1
#> 2 apple 2
#> 3 apple 3
#> 4 banana 4
#> 5 pear 5
#> 6 pear 6
Created on 2021-11-25 by the reprex package (v0.3.0)