I'm trying to make simple conditional swap between two columns,before this i wanted to know which rows will change so i created another column "col3" to monitor this. But it appears it doesn't work all the time
for example
library(tidyverse)
df<-structure(list(in_sample = c(" PG", " T16-14", " T16-14", " Ta-1",
" T5-4", " Bahrain", " Bahrain", " Bahrain", " Bahrain", " Bahrain",
" Bahrain", " Bahrain", " Bahrain", " AS10", " Bahrain", " Bahrain",
" Bahrain", " PG", " Bahrain", " PG", " T3-3", " T14-1", " T7-1",
" AS10", " AS10", " Bahrain", " Bahrain", " Bahrain", " Bahrain",
" Bahrain"), locality = c(" T4-3", " PG", " PG", " PG", " PG",
" Tidal Channel", " Tidal Channel", " Tidal Channel", " Tidal Flat",
" Tidal Flat", " AS10", " Tidal Channel", " Tidal Flat", " Bahrain",
" Foreshore", " MP02", " MP4", " T4-3", " Awaiting Systematics",
" T4-2", " PG", " PG", " PG", " Bahrain", " Bahrain", " MP02",
" MP14", " MP14", " MP14", " Tidal Flat")), row.names = c(NA,
-30L), class = c("tbl_df", "tbl", "data.frame"))
df%>%
mutate(across(where(is.character), str_trim))%>%
mutate(across(where(is.character), str_remove_all, pattern = fixed(" ")))%>%
mutate(col3=if_else(in_sample== c("Bahrain", "PG"), "foo", "bar", missing = NULL))
some instances just refuse to change (see "col3"), but why ?
i've tried several ways but this seems to evade me.
CodePudding user response:
Does %in%
instead of ==
help?
df%>%
mutate(across(where(is.character), str_trim))%>%
mutate(across(where(is.character), str_remove_all, pattern = fixed(" ")))%>%
mutate(col3=if_else(in_sample %in% c("Bahrain", "PG"), "foo", "bar", missing = NULL))