我正在创建一个函数,需要根据用户输入选择特定列。该函数可以工作,只是我试图调用用户使用 ${{input}} 指定的特定列,我收到一条错误消息,表明我的函数中有一个额外的“{”,尽管实际上并不存在。我该如何解决这个问题?为什么我不能使用 df${{input}} 而不触发此错误?
这是一个示例数据集以及在我使用 ${{input}} 之前运行的函数:
#Sample data and packages
library(dplyr)
library(lubridate)
library(ggplot2)
test <- tibble(Month = ymd(c('1990-01-01', '1990-02-01', '1990-03-01', '1990-04-01', '1990-05-01', '1990-06-01')),
score_1 = c(1:6),
score_2 = c(60, 50, 40, 30, NA, 10))
#Working function without using df${{input}} within the geom_line() call
make_chart <- function(data, time_range = c(Week, Month), start_date = NA_Date_) {
data %>%
ggplot(aes(x = {{time_range}})) +
geom_line(data=test[!is.na(test$score_1) & test$Month >= start_date,], aes(y = score_1, colour = "red", linetype = "score 1"), size= 1) +
geom_line(data=test[!is.na(test$score_2) & test$Month >= start_date,], aes(y = score_2, colour = "blue", linetype = "score 2"), size= 1)
}
make_chart(data = test, start_date = '1990-02-06', time_range = Month)
这是我认为应该有效但无效的:
library(dplyr)
library(lubridate)
library(ggplot2)
#Note: the change is within the 2 geom_line lines
make_chart <- function(data, time_range = c(Week, Month), start_date = NA_Date_) {
data %>%
ggplot(aes(x = {{time_range}})) +
geom_line(data=test[!is.na(test$score_1) & test${{time_range}} >= start_date,], aes(y = score_1, colour = "red", linetype = "score 1"), size= 1) +
geom_line(data=test[!is.na(test$score_2) & test${{time_range}} >= start_date,], aes(y = score_2, colour = "blue", linetype = "score 2"), size= 1)
}
make_chart(data = test, start_date = '1990-02-06', time_range = Month)
我理想地想要一个答案来解释为什么 df${{input}} 失败以及此实例的解决方法是什么。谢谢!
最佳答案
根据示例,我们使用单列表示time_range
,将数据过滤
为dat_score1
和dat_score2
>,根据 time_range
以及“score_1”、“score_2”列中的 NA 元素,将其在 geom_line
中用作 data
library(lubridate)
library(dplyr)
library(ggplot2)
make_chart <- function(data, time_range = Month, start_date = NA_Date_) {
dat_score1 <- data %>%
filter(complete.cases(score_1), {{time_range}} >= as.Date(start_date))
dat_score2 <- data %>%
filter(complete.cases(score_2),
{{time_range}} >= as.Date(start_date))
data %>%
ggplot(aes(x = {{time_range}})) +
geom_line(data= dat_score1,
aes(y = score_1, colour = "red",
linetype = "score 1"), size= 1) +
geom_line(data=dat_score2,
aes(y = score_2, colour = "blue", linetype = "score 2"), size= 1)
}
-测试
make_chart(data = test, time_range = Month, start_date = '1990-02-06' )
-输出
关于r - 在 R 中,如何在使用双花括号时选择列?为什么不能将 $ 运算符与大括号一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71833595/