【问题标题】:How to mutate some values of a dataframe based on values from another dataframe column with R如何使用 R 根据来自另一个数据框列的值来改变数据框的某些值
【发布时间】:2020-10-26 23:27:27
【问题描述】:

我想使用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)

【问题讨论】:

标签: r dplyr


【解决方案1】:

if_else 进行类型检查。根据?if_else

与基础 ifelse() 相比,这个函数更加严格。它检查 true 和 false 是否为同一类型。这种严格性使输出类型更可预测,并使其速度更快。

NA 默认返回NA_logical_

typeof(NA)
#[1] "logical"

根据?NA

NA 是一个长度为 1 的逻辑常数,其中包含一个缺失值指示符。 NA 可以强制转换为除 raw 之外的任何其他向量类型。还有其他支持缺失值的原子向量类型的常量NA_integer_、NA_real_、NA_complex_和NA_character_:都是R语言中的保留字。

我们特别需要NA_character_,因为没有强制转换为适当的类型(通常与base Rifelse一起使用)

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_

df1 %>%
  mutate(x = ifelse(str_sub(x,3,4) %in% df2$x & year == 2020, NA, x))

【讨论】:

  • 对其他晦涩的错误消息的好答案。
猜你喜欢
  • 2015-02-23
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2021-06-26
  • 2021-06-06
相关资源
最近更新 更多