【问题标题】:Why am I getting the error 'Unknown or uninitialised column: `x`. ' in R?为什么我收到错误 \'Unknown or uninitialised column: `x`。 \' 在 R 中?
【发布时间】:2023-01-20 23:58:55
【问题描述】:

作为更大函数的一部分,我正在尝试提取唯一的非 na 值,以便我可以遍历该列表。在此功能中,用户应该能够输入其数据框中存在的任何列名。

过去,当我不得不将用户输入转换为字符串时,x_character <- deparse(substitute(x)) 就起作用了。但是,现在我得到 NULL 作为以下函数的输出,并带有 1: Unknown or uninitialised column: x 警告。

为什么 R 不能用 $ 运算符识别这个 x_character?它在过去有效,所以我不确定我是否在这里做错了什么。

#Sample data
library(dplyr)
my_data <- tibble(level = c(rep(c("1st", "2nd", NA, "3rd"), 4), NA, "2nd"),
                  id = c(1:17, 30),
                  score = c(81:97, 70))

这是我的代码:

unique_without_na <- function(data, x) {
  #Pulls out all rows with data in the cut_by argument; drops nas
  x_character <- deparse(substitute(x))
  print(x_character) #just a check
  
  unique_x <- data$x_character[!is.na(data$x_character)] %>% unique()
  unique_x
  
}

unique_without_na(my_data, level) #doesn't work; I've also tried "level" which also fails
unique_without_na(my_data, score) #also doesn't work

【问题讨论】:

  • 您使用的$ 错了。您可以改用[[。 IE。 data[[x_character]]

标签: r function unique custom-function


【解决方案1】:

将它们放在[[ 而不是使用$

unique_without_na <- function(data, x) {
  #Pulls out all rows with data in the cut_by argument; drops nas
  x_character <- deparse(substitute(x))
  print(x_character) #just a check
  
  unique_x <- data[[x_character]][!is.na(data[[x_character]])] %>% unique()
  unique_x
  
}

unique_without_na(my_data, level)
#> [1] "level"
#> [1] "1st" "2nd" "3rd"
unique_without_na(my_data, score) 
#> [1] "score"
#>  [1] 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 70

【讨论】:

猜你喜欢
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2018-10-08
相关资源
最近更新 更多