如何解决如何基于另一个数据框列中的值使用R对数据框的某些值进行突变
我想使用df1$x
变换df2$x
以获得df3
。但是以这种方式使用mutate
时,我肯定是错误的。
library(tidyverse)
df1 <- tibble(year = c(2019,2019,2020,2020),x = c("0123","0222","0144","0124"))
df2 <- tibble(x = c("22","24"))
# I want to obtain
df3 <- tibble(year = c(2019,NA))
# but this mutate does not work
df1 %>%
mutate(x = if_else(str_sub(x,3,4) %in% df2$x & year == 2020,NA,x))
#> Error: Problem with `mutate()` input `x`.
#> x `false` must be a logical vector,not a character vector.
#> i Input `x` is `if_else(str_sub(x,x)`.
Created on 2020-10-26 by the reprex package (v0.3.0)
解决方法
if_else
会进行类型检查。根据{{1}}
与基本的ifelse()相比,此功能更为严格。它检查true和false是同一类型。这种严格性使输出类型更可预测,并且速度更快。
和?if_else
默认返回NA
。
NA_logical_
根据typeof(NA)
#[1] "logical"
NA是长度为1的逻辑常数,其中包含一个缺失值指示符。 NA可以强制为除raw以外的任何其他向量类型。其他原子向量类型的常量NA_integer_,NA_real_,NA_complex_和NA_character_也支持缺失值:所有这些都是R语言中的保留字。
我们特别需要?NA
,因为没有强制使用适当的类型(通常适用于NA_character_
base R
)
ifelse
因此,最好使用与typeof(NA_character_)
#[1] "character"
相匹配的适当类型
NA
library(dplyr)
df1 %>%
mutate(x = if_else(str_sub(x,3,4) %in% df2$x &
year == 2020,NA_character_,x))
没问题,因为ifelse
自动转换为NA
NA_character_
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。