Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用R根据另一个数据帧列的值对数据帧的某些值进行变异_R_Mutate - Fatal编程技术网

如何使用R根据另一个数据帧列的值对数据帧的某些值进行变异

如何使用R根据另一个数据帧列的值对数据帧的某些值进行变异,r,mutate,R,Mutate,我想使用df2$x转换df1$x,以获得df3。但是我用这种方式使用mutate肯定是错的 library(tidyverse) df1 <- tibble(year = c(2019, 2019, 2020, 2020), x = c("0123", "0222", "0144", "0124")) df2 <- tibble(x = c("22", &q

我想使用
df2$x
转换
df1$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, 2019, 2020, 2020),
              x = c("0123", "0222", "0144", 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, 3, 4) %in% df2$x & year == 2020, NA, x)`.
Created on 2020-10-26 by the reprex package (v0.3.0)
库(tidyverse)
df1 x`false`必须是逻辑向量,而不是字符向量。
#>我输入的'x'是'if_else(str_sub(x,3,4)%in%df2$x&year==2020,NA,x)`。
由reprex软件包(v0.3.0)于2020年10月26日创建

如果没有,则
进行类型检查。根据
?如果其他

typeof(NA_character_)
#[1] "character"
与基ifelse()相比,此函数更严格。它检查true和false是否为同一类型。这种严格性使得输出类型更可预测,并且速度更快

默认情况下,
NA
返回
NA\u逻辑

typeof(NA)
#[1] "logical"
根据
?NA

NA是长度为1的逻辑常数,其中包含缺少的值指示符。NA可以强制为除raw之外的任何其他向量类型。还有其他支持缺失值的原子向量类型的常量NA_integer_uu、NA_real_u、NA_complex_u和NA_character_u:所有这些都是R语言中的保留字

我们特别需要
NA\u字符
,因为没有强制到适当的类型(这通常与
base R
一起工作)

因此,最好使用适当的匹配类型
NA

library(dplyr)
df1 %>%
    mutate(x = if_else(str_sub(x,3,4) %in% df2$x &
              year == 2020, NA_character_, x))
ifelse
没有这个问题,因为
NA
自动转换为
NA\u字符

df1 %>%
  mutate(x = ifelse(str_sub(x,3,4) %in% df2$x & year == 2020, NA, x))
有两个(或更多)类似的问题和