【发布时间】: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