Hello,
I want to do next thing: " if cell contains specific text, then i want to written another text in this cell." For example: text in the cell is "unknown text here".
I want to do next: If cell contains word "unknown" then write word "fine".
I think something like this will do what you want:
library(data.table)
dat1 <- data.table( aa = c("yes", "no", "yes", "no"), bb = 1:4)
dat1[, aa := fcase(
aa == "yes", "HIT",
aa != "yes", aa
)]
Thank you for your reply. Actually, I need something else, but thanks again.
Perhaps you could explain a bit more what you need?
For example:
dat1 <- data.table( aa = c("red pen", "green pencil", "yellow chair", "white book"), bb = 1:4)
if cell contains "red" - then i want to fill this cell with "writing";
if cell contains "green" - to fill this cell with "drawing";
if cell contains "yellow" - to fill this cell with "sitting";
if cell contains "white" -to fill this cell with "reading";
I need something like this.
Final result:
dat1 <- data.table( aa = c("writing", "drawing", "sitting", "reading"), bb = 1:4)
I, clearly, misread your first post. I think this will do what you want.
dat1 <- data.table( aa = c("red pen", "green pencil", "yellow chair", "white book"), bb = 1:4)
dat1[, aa := fcase(
grepl("red", aa), "writing",
grepl("green", aa), "drawing",
grepl("yellow", aa), "sitting",
grepl("white", aa), "reading"
)]
You could also use dplyr::case_when
to recode the values.
# package libraries
library(tidyverse)
# sample data
dat1 <- tibble(
aa = c("red pen", "green pencil", "yellow chair", "white book"),
bb = seq(1, 4, 1)
)
# view
dat1
#> # A tibble: 4 × 2
#> aa bb
#> <chr> <dbl>
#> 1 red pen 1
#> 2 green pencil 2
#> 3 yellow chair 3
#> 4 white book 4
# code new variable, code according to rules for renaming
dat1 %>%
mutate(
code = case_when(
stringr::str_detect(aa, "red") ~ "writing",
stringr::str_detect(aa, "green") ~ "drawing",
stringr::str_detect(aa, "yellow") ~ "sitting",
stringr::str_detect(aa, "white") ~ "reading"
)
)
#> # A tibble: 4 × 3
#> aa bb code
#> <chr> <dbl> <chr>
#> 1 red pen 1 writing
#> 2 green pencil 2 drawing
#> 3 yellow chair 3 sitting
#> 4 white book 4 reading
# alternatively, if you wanted to change the value
# instead of creating a new variable
dat1 %>%
mutate(
aa = case_when(
stringr::str_detect(aa, "red") ~ "writing",
stringr::str_detect(aa, "green") ~ "drawing",
stringr::str_detect(aa, "yellow") ~ "sitting",
stringr::str_detect(aa, "white") ~ "reading"
)
)
#> # A tibble: 4 × 2
#> aa bb
#> <chr> <dbl>
#> 1 writing 1
#> 2 drawing 2
#> 3 sitting 3
#> 4 reading 4
Created on 2024-01-11 with reprex v2.0.2
Thanks a lot. It works well.
Thanks a lot. I will try.
This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.