为什么有些字符串即使在删除所有空格后也没有改变

why are some strings not changing even after removing all whitespaces

我正在尝试在两列之间进行简单的条件交换,在此之前我想知道哪些行会发生变化,所以我创建了另一列“col3”来监视它。但是好像不是一直有效

例如

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))

有些实例只是拒绝更改(参见“col3”),但为什么呢?

我已经尝试了几种方法,但这似乎让我望而却步。

%in% 代替 == 有帮助吗?

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))