R 在ggplot2中使用colnames()作为xlab参数在使用LAPPY时返回NAs

R 在ggplot2中使用colnames()作为xlab参数在使用LAPPY时返回NAs,r,function,ggplot2,data-visualization,lapply,R,Function,Ggplot2,Data Visualization,Lapply,我正在尝试使用以下函数创建一个函数,该函数在一个数据帧中绘制多个列(总共36列): big5p1 <- function(i) { ggplot(big5_pos, aes(x= i, y = title)) + geom_bar(stat="identity", width=0.5) + xlab(colnames(big5_pos)[i]) + #Issues with NAs ylab("P

我正在尝试使用以下函数创建一个函数,该函数在一个数据帧中绘制多个列(总共36列):

big5p1 <- function(i) {
        ggplot(big5_pos, aes(x= i, y = title)) +
        geom_bar(stat="identity", width=0.5) +
        xlab(colnames(big5_pos)[i]) + #Issues with NAs
        ylab("Position") +
        geom_vline(xintercept = mean(i), color="red")
  }

lapply(big5_pos[2:3], big5p1) 

big5p1将函数更改为接受列名

library(ggplot2)

big5p1 <- function(i) {
  ggplot(big5_pos, aes(x = .data[[i]], y = title)) +
    geom_bar(stat="identity", width=0.5) +
    xlab(i) + 
    ylab("Position") +
    geom_vline(xintercept = mean(big5_pos[[i]], na.rm = TRUE), color="red")
}

result <- lapply(names(big5_pos)[2:3], big5p1) 
库(ggplot2)

big5p1我们可以将列名转换为
sym
bols,并使用(
!!
)进行计算

库(ggplot2)

谢谢你!这修复了x标签,但现在平均值的xintercept没有出现。geom_vline(xintercept=mean(.data[[i]]),color=“red”)@snaccidents尝试更新答案。是的,这确实有效!!谢谢:)
library(ggplot2) 
big5p1 <- function(nm) {
  ggplot(big5_pos, aes(x =  !! rlang::sym(nm), y = title)) +
   geom_bar(stat = "identity", width = 0.5) +
   xlab(nm) + 
   ylab("Position") +
   geom_vline(xintercept = mean(big5_pos[[nm]], na.rm = TRUE), color="red")
   }
result <- lapply(names(big5_pos)[2:3], big5p1)