gpt4 book ai didi

r - 循环遍历数据帧列表以在 R 中创建图形

转载 作者:行者123 更新时间:2023-12-02 00:54:26 25 4
gpt4 key购买 nike

我使用 xyplot 创建了一个点阵散点图,该散点图被分为不同的类别。现在我正在尝试为散点图中的每个类别创建一个 hexplot。我可以对变量进行硬编码,但我更愿意在循环中执行此操作,因为我会多次执行此操作,这将有新的类别。

我从一个看起来像这样的表格开始

 Name     Category     Value1      Value2
sample1 cat1 10 1.5
sample2 cat2 10 1.5
sample3 cat3 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5
sample6 cat2 10 1.5
sample7 cat3 10 1.5

我能够使用

创建数据框列表
testing <- split(Mydata, Mydata$Category)

然后我可以创建一个情节

testing2 <- as.data.frame(testing[["cat1"]]) #I keep on needing to change this for each Category that I have
ggplot(testing2, aes(x = testing2[,3], y = testing2[,4])) +
geom_hex(bins = 30)

测试 2 看起来像这样

 Name     Category     Value1      Value2
sample1 cat1 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5

我试过了

for(i in testing){
testing3 <- i
xtra <- ggplot(testing3, aes(x = testing3[,3], y = testing3[,4])) + geom_hex(bins = 30)
xtra
}

最终 xtra 成为列表中的最后一个数据帧。

有人可以帮我解决这个问题吗?我希望能够创建绘图而不必每次都更改 $Category,因为每次我想要执行此操作时都有 >50 个类别。

--编辑1根据建议,我创建了一个函数;

myFirstFun <- function(column)
{
testing2 <- as.data.frame(testing[[column]])
column <- enquo(column)
ggplot(testing2, aes_string(x ="Value1", y = "Value2", group = column)) +
geom_hex(bins = 30)
}

还有这个;

myFirstFun("cat1")

产生这个;

 Name     Category     Value1      Value2
sample1 cat1 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5

但是当我尝试使用 for 循环时;

for(i in categorynames){###categorynames is a vector that has all my categorynames
myFirstFun(i)
}

它只会生成列表中的最后一个图形。我将如何生成 n 个图表(n = 我的类别数)?没有我手动做

myFirstFun("cat1")
myFirstFun("cat2")
myFirstFun("cat3")
...

最佳答案

您可以构建一个函数,在其中使用 dplyr::filter 选择所需的 Category,然后进行绘图。

要遍历每个 Category,请使用 purrr::map 并将所有结果存储在列表中。从那里您可以打印您选择的情节或将它们全部合并到一页或 multiple pages

library(tidyverse)

df <- read.table(text = "Name Category Value1 Value2
sample1 cat1 11 2.5
sample2 cat2 13 1.5
sample3 cat3 12 3.5
sample4 cat1 15 6.5
sample5 cat1 17 4.5
sample6 cat2 14 7.5
sample7 cat3 16 1.5",
header = TRUE, stringsAsFactors = FALSE)

cat_chart1 <- function(data, category){

df <- data %>%
filter(Category == category)

plot1 <- ggplot(df, aes(x = Value1, y = Value2)) +
geom_hex(bins = 30)

return(plot1)
}

# loop through all Categories
plot_list <- map(unique(df$Category), ~ cat_chart1(df, .x))
plot_list[[1]]

# combine all plots
library(cowplot)
plot_grid(plotlist = plot_list, ncol = 2)

reprex package 创建于 2019-04-04 (v0.2.1.9000)

关于r - 循环遍历数据帧列表以在 R 中创建图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55519709/

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