[英]Plotting graphs using loops in R
我的代碼如下,我正在嘗試使用循環讓 R 繪制 24 個不同的圖形,但我不斷收到錯誤代碼“要替換的項目數不是替換長度的倍數”
array.1 <- array(dim=c(24,2))
array.1[,1] <- c("g1","g2","g3","g4","g5","g6","g7","g8","g9","g10","g11","g12","g13","g14","g15","g16","g17","g18","g19","g20","g21","g22","g23","g24")
array.1[,2] <- c("fiveac" ,"fiveem", "k3en"," k3ma", "k3sc", "k3EnMaSc", "gender", "SECshort", "hiquamum", "singlepar", "house", "fsm", "parasp","computer", "tuition" ,"pupasp" ,"homework", "attitude" ,"sen" ,"truancy" ,"absent" ,"exclude", "IDACI_n", "FSMband")
for(i in 1:24){
array.1[i,1] <- ggplot(ks4.dat, aes(x=array.2[i,2], y=ks4score))
array.1[i,1] <- array.1[i,1] + geom_point()
array.1[i,1] <- array.1[i,1] + geom_smooth(method="lm")
}
簡單的答案是您不能將 ggplot 存儲在數組中:
library(ggplot2)
a <- array(1, dim = c(1,1));
d <- data.frame(x = rnorm(10), y = rnorm(10));
g <- ggplot(d, aes(x = x, y = y)) + geom_point()
a[1, 1] <- g
#> Error in a[1, 1] <- g: number of items to replace is not a multiple of replacement length
由reprex 包(v0.3.0) 於 2020 年 2 月 20 日創建
也許您可以嘗試使用命名列表?
顯然,我沒有您的數據可供使用,但您可以嘗試:
glist <- list()
for(i in 1:24){
gglist[[i]] <- ggplot(ks4.dat, aes(x=array.1[i,2], y=ks4score))
gglist[[i]] <- gglist[[i]] + geom_point()
gglist[[i]]] <- gglist[[i]] + geom_smooth(method="lm")
}
我還注意到您試圖在調用array.2
索引一個名為array.2
的對象。 這是一個錯誤嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.