0

我正在尝试使用以下函数创建一个在数据框中绘制多列(总共 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) 

当我检查时,colnames(big5_pos[2:36])我确实得到了每列的正确字符名称列表。但是,当使用 apply 时,只有一些 xlab 被正确打印,其余的只有 NA 作为标签。不知道我忽略了什么,但任何帮助或建议将不胜感激!

4

2 回答 2

1

更改您的函数以接受列名。

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) 
于 2020-12-23T11:53:43.300 回答
0

我们可以将列名转换为bols 并使用 ( )sym进行评估!!

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) 
于 2020-12-23T17:19:13.983 回答