【问题标题】:R dplyr strange filtering on data frame (reproducible code) [duplicate]R dplyr对数据帧的奇怪过滤(可重现的代码)[重复]
【发布时间】:2018-08-16 09:29:23
【问题描述】:

这似乎是 dplyr 过滤中非常奇怪的行为,有人可以告诉我我在哪里出错,或者您的机器上是否也发生了以下情况。先感谢您。

当我尝试使用 dplyr 过滤数据框时,它在使用原始字符串时工作正常,但在粘贴或使用变量时(至少在我的机器上)没有。

library(dplyr)

###Recreate data
country <- "ZAF"
df <- data.frame(iso3c=as.character("ZAF"), 
                   country=as.character("South Africa"), 
                   level=as.integer(4),stringsAsFactors = FALSE)

问题是这些过滤掉了 ZAF 行,而不是保留它。

###Filters out the ZAF row, none of these work
df.nowork1 <- filter(df, iso3c==country)
df.nowork2 <- filter(df, iso3c==paste(country))
df.nowork3 <- filter(df, iso3c==paste0("'",country,"'"))

这些按照我希望它们对变量执行的操作:

##Works 
df.works <- filter(df, iso3c=="ZAF")
df.works2 <- filter(df, iso3c==paste("ZAF"))

【问题讨论】:

  • 请不要用您的答案编辑您的问题。如果您自己找到了解决方案,欢迎您在下面回答;否则,您可以通过单击答案左侧的复选标记来选择其他成员的答案作为帮助您的答案。已编辑以包含解决方案的问题可能会回滚到以前的状态。

标签: r dataframe filter dplyr


【解决方案1】:

我们可以通过指定不使用 bang bang (!!) 对数据集的列进行评估来做到这一点

df %>%
   filter(iso3c== !!country)
#  iso3c      country level
#1   ZAF South Africa     4

或者另一种方法是从.GlobalEnv中提取对象

filter(df, iso3c== .GlobalEnv$country)
#  iso3c      country level
#1   ZAF South Africa     4

这里,'df'有一个名为'country'的列,所以在环境中,在指定'country'时,它检查的是列而不是数据集之外的对象

df %>%
    select(country)
#        country
#1 South Africa

【讨论】:

  • 谢谢!为什么是这样?您的解决方案有效,但我很困惑为什么您不能将国家/地区用作原始格式的变量
  • @NealBarsch 因为它会在 'df' 的环境中查找,其中 'country' 是一列,而不是您在数据集环境之外指定的对象 country
  • 什么是砰砰!!在做什么?
  • @NealBarsch 它评估对象并从外部获取值
  • 我明白了。因为列与变量同名
【解决方案2】:

我对保持 colname 和 variable 同名感到羞耻。

ctry <- country
works <- filter(df, iso3c==ctry)

【讨论】:

  • 我以为您是故意保留它并想了解如何评估这些情况。无论如何,!! 也会在这里
  • 是的,我喜欢 globals 方法,所以我在这个过程中学到了一些东西:)
猜你喜欢
  • 2019-08-08
  • 1970-01-01
  • 2019-06-15
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多