gpt4 book ai didi

r - 使用 dplyr select() 在 for 循环中生成 ggplot 对象时最终对象出错

转载 作者:行者123 更新时间:2023-12-03 08:11:22 25 4
gpt4 key购买 nike

我想使用数据框中的多对变量绘制许多图,所有变量都具有相同的 x。我将这些图存储在一个命名列表中。为简单起见,下面是每个图中只有 1 个变量的示例。

此功能的关键是 select()显然这里没有必要调用,但它与我的实际数据有关。

函数的主体对每个变量都可以正常工作,但是当我循环遍历变量列表时,列表中的最后一个总是产生

Error in get(ll): object 'd' not found.

(或者最后一个变量,如果不是“d”)。更换data <- df %>% select(x,ll)data <- df避免了错误。

## make data
df2 <- data.frame(x = 1:10,
a = 1:10,
b = 2:11,
c = 101:110,
d = 10*(1:10))

## make function
testfun <- function(df = df2, vars = letters[1:4]){
## initialize list to store plots
plotlist <- list()

for (ll in vars){
## subset data
data <- df %>% select(x, ll) ## comment out select() to get working function
# print(data) ## uncomment to check that dataframe subset works correctly

## plot variable vs. x
p <- ggplot(data,
aes(x = x, y = get(ll))) +
geom_point() +
ylab(ll)

## add plot to named list
plotlist[[ll]] <- p
# print(p) ## uncomment to see that each plot is being made
}
return(plotlist) ## unnecessary, being explicit for troubleshooting
}

## use function
pl <- testfun(df2)
## error ?
pl

我有一个解决方法可以避免 select()通过重命名我的实际数据框中的变量,但我很好奇为什么这不起作用?有什么想法吗?

最佳答案

问题是我们无法在“编程”范例中使用 get 访问 dplyr/tidyverse 数据。相反,我们应该使用非标准评估来访问数据。我在下面提供了一个简化的函数(最初我认为这是一个函数屏蔽问题,因为我快速浏览了这个问题)。

testfun <- function(df = df2, vars = letters[1:4]){


lapply(vars, function(y) {
ggplot(df,
aes(x = x, y = .data[[y]] )) +
geom_point() +
ylab(y)

})


}

调用

plots <- testfun(df2)
plots[[1]]

编辑

由于OP想知道问题是什么,我根据要求使用了传统循环

testfun2 <- function(df = df2, vars = letters[1:4]){
## initialize list to store plots
plotlist <- list()

for (ll in vars){
## subset data
d_t <- df %>% select(x, ll) ## comment out select() to get working function
# print(data) ## uncomment to check that dataframe subset works correctly
## plot variable vs. x
p <- ggplot(d_t,
aes(x = x, y = .data[[ll]])) +
geom_point() +
ylab(ll)
## add plot to named list
plotlist[[ll]] <- p
## uncomment to see that each plot is being made
}
plotlist

}
pl <- testfun2(df2)
pl[[1]]

get 不起作用的原因是我们需要使用非标准评估,如文档 state 所示。 。使用相关问题get可能是useful .

第一个图

enter image description here

关于r - 使用 dplyr select() 在 for 循环中生成 ggplot 对象时最终对象出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70722735/

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