gpt4 book ai didi

r - 为什么我在按 'with' 选择时得到 NA

转载 作者:行者123 更新时间:2023-12-04 02:36:11 24 4
gpt4 key购买 nike

作为@allan-cameron 在 Most concise way to get a value from within a tibble 中出色回答的后续

如果我将一些 NA 添加到 band-instruments

bandy <- tibble(name = c("John", "Paul", "Keith", "Eric", NA), 
plays = c("guitar", "bass", "guitar", NA, "kazoo"))

with(bandy, plays[name == "John"])
# [1] "guitar" NA

with(bandy, name[plays == "guitar"])
# [1] "John" "Keith" NA

有人可以解释为什么我要退回那些 NA 吗?避免返回的最优雅方式是什么?

最佳答案

我认为那些 NA 与 with 函数或 tibble 格式无关。参见示例:

x <- c(1, 2, NA)
x[x == 1]
#> [1] 1 NA

reprex package 创建于 2020-05-10 (v0.3.0)

对于==函数的帮助页面我们可以阅读:

Missing values (NA) and NaN values are regarded as non-comparable even to themselves, so comparisons involving them will always result in NA.

[函数的帮助页面我们可以读到:

When extracting, a numerical, logical or character NA index picks an unknown element and so returns NA in the corresponding element of a logical, integer, numeric, complex or character result, and NULL for a list. (It returns 00 for a raw result.)

所以这就是代码返回 NA 的原因。

IMO 避免这些 NA 的最简单方法如下:

library(tibble)
bandy <- tibble(name = c("John", "Paul", "Keith", "Eric", NA),
plays = c("guitar", "bass", "guitar", NA, "kazoo"))

with(bandy, plays[name == "John" & !is.na(name)])
#> [1] "guitar"
with(bandy, name[plays == "guitar" & !is.na(plays)])
#> [1] "John" "Keith"

reprex package 创建于 2020-05-10 (v0.3.0)

关于r - 为什么我在按 'with' 选择时得到 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61714849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com