gpt4 book ai didi

r - dplyr::filter() 的意外行为

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

谢谢你的时间。

这可能是我忽略的一个明显问题,但我今天早上使用 dplyr::filter() 遇到了一些意想不到的行为。 .

使用 filter()似乎有效,除非列名和对象名相同。有关详细信息,请参阅以下示例。

我在期待 data只返回 data$year 所在的行匹配 yeardata$month匹配 month ,但它会返回所有值。

我以前做过很多次同样的操作,所以我不确定为什么这次会发生。

重命名时 monthmonth_by_a_different_name ,一切都按预期工作。有任何想法吗?谢谢你的时间。

library(tidyverse)

# Example data
data <-
tibble(
year = c(2019, 2018, 2017),
month = c("January", "February", "March"),
value = c(1, 2, 3)
)


# -----------------------------------------------

# Values to filter by
year <- 2019
month <- "February"

# Assigning year and month to a different object name
year_by_a_different_name <- year
month_by_a_different_name <- month


# -----------------------------------------------

# Filtering using year and month doesn't work
data %>%
dplyr::filter(year == year) # Doesn't work

data %>%
dplyr::filter(month == month) # Doesn't work


# -----------------------------------------------

# Filtering using different names works
data %>%
filter(year == year_by_a_different_name) # Works

data %>%
filter(month == month_by_a_different_name) # Works


# -----------------------------------------------

# Using str_detect() also doesn't work for month
data %>%
dplyr::filter(str_detect(month, month))


# -----------------------------------------------

# Works with base R
data[data$month == month, ]
data[data$year == year, ]


# -----------------------------------------------

# Objects are of same class
class(data$year) == class(year) # TRUE
class(data$month) == class(month) # TRUE

最佳答案

TLDR:使用 filter(year == !!year)
这是由 dplyr 的非标准评估 (NSE) 引起的 - 您是否指的是 df$year 模棱两可。或您的外部变量 year .
NSE 使用所谓的“quosures”来推断当您写 year 时在 LHS 上,您指的是管道输入列的列。这种引用技巧允许您引用 tidyverse 系列包中管道输入范围内定义的名称(即数据框列),并通过 (i) 避免输入引用使您的生活变得更加轻松 -标记无处不在,并且 (ii) 允许 Rstudio 为您提供自动完成建议。

但是,就您这里的情况而言,year RHS 上的意思是指输入 data.frame 之外的东西,即使该名称也在那里使用。在这种情况下,!! ("bangbang") 运算符告诉 NSE 您的变量不应被引用,而应按原样进行评估。

您可以在这里找到更多信息:https://dplyr.tidyverse.org/articles/programming.html ,尤其是关于“不同表达”的部分。从上面的小插图:

In dplyr (and in tidyeval in general) you use !! to say that you want to unquote an input so that it’s evaluated, not quoted. This gives us a function that actually does what we want.

关于r - dplyr::filter() 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55614439/

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