我试图在两列之间进行简单的条件交换,在此之前,我想知道哪些行将更改,因此我创建了另一列"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"),但为什么呢?
我试过几种方法,但这似乎回避了我。
发布于 2021-11-10 10:50:07
%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))https://stackoverflow.com/questions/69911863
复制相似问题