分配给列表和绘图在循环中不起作用
Assigning to list and plotting don't work in loop
假设我有以下功能:
library(ggplot2)
library(patchwork)
subplots <- function(data) {
lst <- list()
# Assigning first and second variable to the list
for (i in 1:2) {
lst[[i]] <- ggplot() +
aes(x = 1:length(data[, i]), y = data[, i]) +
geom_line()
}
# Plotting variables stored in the list
wrap_plots(lst)
}
此代码的主要目的是获取数据框并并排绘制第一个和第二个变量的图。但是,如果我 运行 此代码在相同的数据上:
sed.seed(42)
vec_1 <- rnorm(100)
vec_2 <- runif(100)
df <- data.frame(vec_1, vec_2)
subplots(df)
我获得了两次第二个变量图,而不是第一次和第二次。
你知道怎么修复吗?我是不是分配错了?
您的列表分配很好,但您的 ggplot()
调用语法不正确。
尝试:
subplots <- function(data) {
lst <- list()
# Assigning first and second variable to the list
for (i in 1:2) {
lst[[i]] <- ggplot(data.frame(x = 1:length(data[, i]), y = data[, i]), aes(x = x, y = y)) +
geom_line()
}
# Plotting variables stored in the list
wrap_plots(lst)
}
假设我有以下功能:
library(ggplot2)
library(patchwork)
subplots <- function(data) {
lst <- list()
# Assigning first and second variable to the list
for (i in 1:2) {
lst[[i]] <- ggplot() +
aes(x = 1:length(data[, i]), y = data[, i]) +
geom_line()
}
# Plotting variables stored in the list
wrap_plots(lst)
}
此代码的主要目的是获取数据框并并排绘制第一个和第二个变量的图。但是,如果我 运行 此代码在相同的数据上:
sed.seed(42)
vec_1 <- rnorm(100)
vec_2 <- runif(100)
df <- data.frame(vec_1, vec_2)
subplots(df)
我获得了两次第二个变量图,而不是第一次和第二次。
你知道怎么修复吗?我是不是分配错了?
您的列表分配很好,但您的 ggplot()
调用语法不正确。
尝试:
subplots <- function(data) {
lst <- list()
# Assigning first and second variable to the list
for (i in 1:2) {
lst[[i]] <- ggplot(data.frame(x = 1:length(data[, i]), y = data[, i]), aes(x = x, y = y)) +
geom_line()
}
# Plotting variables stored in the list
wrap_plots(lst)
}