[英]How to get each vector / column name inside a map function in r?
我是 R 新手並應用plotting function
來查看each factor column
的all factors
的counts
。
df
install.packages("gapminder")
library(gapminder)
gapminder %>% head()
########### output ###############
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
Afghanistan Asia 1952 28.801 8425333 779.4453
Afghanistan Asia 1957 30.332 9240934 820.8530
Afghanistan Asia 1962 31.997 10267083 853.1007
Afghanistan Asia 1967 34.020 11537966 836.1971
Afghanistan Asia 1972 36.088 13079460 739.9811
Afghanistan Asia 1977 38.438 14880372 786.1134
問題:我無法在下面的代碼中獲取列名作為圖表標題:
gapminder %>%
select_if(is.factor) %>%
map(function(feature) {
count(data.frame(x = feature), x) %>%
ggplot(aes(x = x, y = n)) +
geom_col() +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90)) +
# issue here in getting column name as chart title
labs(title = colnames(feature))
# labs(title = colnames(x))
})
看起來是個小問題,但無法弄清楚如何為每個圖表獲取相應的列名
也許嘗試這種方法作為您的選擇。 使用因子變量重塑數據,然后匯總以獲得計數。 在為每個變量設置標題時,使用 facet 會有所幫助。 這里的代碼:
library(gapminder)
library(tidyverse)
#Code
gapminder %>%
select_if(is.factor) %>%
pivot_longer(everything()) %>%
group_by(name,value) %>%
summarise(N=n()) %>%
ggplot(aes(x = value, y = N)) +
geom_col(fill='purple',color='black') +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90)) +
facet_wrap(.~name,nrow = 1,scales = 'free')
輸出:
您可以使用imap
而不是map
,這將使您可以訪問列名稱和值。
library(tidyverse)
list_plot <- gapminder %>%
select(where(is.factor)) %>%
imap(function(feature_value, feature_name) {
count(data.frame(x = feature_value), x) %>%
ggplot(aes(x = x, y = n)) +
geom_col() +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90)) +
labs(title = feature_name)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.