2017-09-02 101 views
0

因此,這裏是我的代碼提取R中的列名與lapply

h <- lapply(select(winedata, -quality), function(variable){ 
return(ggplot(aes(x = variable), data = winedata) + 
geom_histogram(bins = 30) + xlab(variable))}) 

有一個問題,那就是xlab(變量)顯示第一列作爲x軸標題的值,如果我選擇變量[2]它顯示第二列的值作爲x軸標題。我如何獲得它將列名稱作爲X軸標題。名字(變量)似乎並沒有工作

+3

請參閱[MCVE。 –

+6

你可以迭代'names(winedata)'並使用'aes_string',但更好的方法是重塑長表單並使用'facet_wrap'來將所有的圖表合併爲一個,例如'庫(tidyverse); winedata%>%gather(變量,值)%>%ggplot(aes(value))+ geom_histogram()+ facet_wrap(〜變量)' – alistaire

回答

0

您可以使用Map

library(ggplot2) 
library(dplyr) 

Map(function(var, names){ 
    return(ggplot(iris, aes(x = var)) + 
      geom_histogram(bins = 30) + xlab(names))}, 
    select(iris, -Species), names(iris)[1:4]) 

Map基本上是mapplySIMPLIFY=FALSE,這需要多個輸入,並返回一個列表。

enter image description here enter image description here enter image description here enter image description here

+0

This works,thank you。我將更多地關注Map函數。 – Mark

+0

@Mark如果您認爲此答案有幫助,請隨時接受,以便其他人可以看到:) – useR