Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何循环df子集设置和ggplot?_Loops_Ggplot2_Subset - Fatal编程技术网

Loops 如何循环df子集设置和ggplot?

Loops 如何循环df子集设置和ggplot?,loops,ggplot2,subset,Loops,Ggplot2,Subset,我希望在循环中包含子设置,以便使用R生成多个ggplot。我试着采用其他帖子中建议的解决方案,但都不起作用 name char stat z n1 c1 2.1 1 n1 c2 1.9 2 n1 c3 2.0 4 n1 c4 3.4 4 n2 c1 1.1 2 n2 c2 1.2 1 n2 c3 2.0 3 n2 c4 1.8 4 n3 c1 5.1

我希望在循环中包含子设置,以便使用R生成多个ggplot。我试着采用其他帖子中建议的解决方案,但都不起作用

name  char  stat  z
n1    c1    2.1   1
n1    c2    1.9   2
n1    c3    2.0   4
n1    c4    3.4   4
n2    c1    1.1   2
n2    c2    1.2   1
n2    c3    2.0   3
n2    c4    1.8   4
n3    c1    5.1   2
n3    c2    3.3   3
n3    c3    4.7   1
n3    c4    0.5   2
高达n12(可能更多)

目前,我根据需要的名称手动对数据帧进行子集划分,并生成其绘图:

n1 <- df[df$name=="n1",]
p1 <- ggplot(n1, aes(x=char, y=stat)) +
  geom_col(fill = palette[n1$z])
p1
但它又回来了

Error: Can't use NA as column index with `[` at positions 1, 2, 3, 4, 5, and 16 more.
Error in ggplot(var, aes(x = char, y = stat)) : 
  object 'n1' not found.
类似地,我尝试创建一个函数,以便使用Lappy循环它:

draft <- function(var) {
  ggplot(var, aes(x=char, y=stat))
}
draft(n1)

我尝试了一些其他的解决方案,但仍然不起作用。你有什么建议吗?

我根据这个博客上的信息构建了一个解决方案:

您可以首先创建一个函数,该函数应为其提供子集合。并使用purrr::map函数进行迭代

df <- tibble(name = c("n1", "n1","n1", "n1", "n2","n2","n2","n2","n3","n3","n3","n3"),
            char = c("c1", "c2", "c3", "c4","c1", "c2", "c3", "c4","c1", "c2", "c3", "c4"),
            stat = c(2.1, 1.9,2.0,3.4,1.1,1.2,2.0,1.8,5.1,3.3,4.7,0.5),
            z = c(1,2,4,4,2,1,3,4,2,3,1,2))


plot_function <- function(sub_set) {
  n <- df %>% filter(name %in% c(sub_set))
  p <- n %>% ggplot(aes(x=char, y=stat, fill = z)) +
    geom_col()
} 

uniq_names <- df %>% distinct(name)
all_groups <- uniq_names$name
all_groups = set_names(all_groups)

all_plots <- map(all_groups, ~plot_function(.x))

all_plots$n1
all_plots$n2
all_plots$n3

df
df <- tibble(name = c("n1", "n1","n1", "n1", "n2","n2","n2","n2","n3","n3","n3","n3"),
            char = c("c1", "c2", "c3", "c4","c1", "c2", "c3", "c4","c1", "c2", "c3", "c4"),
            stat = c(2.1, 1.9,2.0,3.4,1.1,1.2,2.0,1.8,5.1,3.3,4.7,0.5),
            z = c(1,2,4,4,2,1,3,4,2,3,1,2))


plot_function <- function(sub_set) {
  n <- df %>% filter(name %in% c(sub_set))
  p <- n %>% ggplot(aes(x=char, y=stat, fill = z)) +
    geom_col()
} 

uniq_names <- df %>% distinct(name)
all_groups <- uniq_names$name
all_groups = set_names(all_groups)

all_plots <- map(all_groups, ~plot_function(.x))

all_plots$n1
all_plots$n2
all_plots$n3