我想使用函數'ggplot'將函數圖分配給函數'eval'創建的對象。該對象位於一個循環中,因此定義爲一個列表。在循環的每一輪中,應該使用變量'list_pos'將該圖保存爲列表的一個元素。錯誤'下標越界'使用eval() - 基於assign()的函數 - 循環中的函數
目標是創建三個不同的列表'Graphs_A','Graphs_B'和'Graphs_C',每個三個不同的圖作爲元素保存。因此,作爲一個結果,我可以只運行
Graphs_A
的R-代碼如下所示調用特定亞羣的地塊,例如A組,在一次。在我的例子中,我總是將相同的圖表分配給這些元素,當然,對於我的真實數據集,情況並非如此。
###### Example #####
# Load packages
install.packages('ggplot2')
library(ggplot2)
# Creating data
names <- c("A","B","C")
numbers <- c(1,2,3)
df <- data.frame(
x = c(1, 2, 3, 4, 5, 6, 7, 8),
y = c(3, 2, 4, 4, 6, 8, 9, 8)
)
# Loop to assign ggplot to elements of list
for(j in names){
assign(paste("Graphs_", j, sep=""), list())
list_pos <- 0
for(i in numbers){
list_pos <- list_pos + 1
assign(
eval(parse(text=paste("Graphs_", j, sep="")))[[list_pos]],
ggplot() + geom_point(data=df, aes(x=x, y=y)) # Plot depends in real data set on value of i
)
}
}
我總是得到一個錯誤'下標越界'。我嘗試了不同的東西,如重新定義列表
assign(paste("Graphs_", j, sep=""), list("X","Y","Z"))
但它沒有幫助將圖分配給列表中的元素。我該如何處理這個問題?
忘記存在'parse'和'assign'。除非你對R有更多的經驗,否則你將不會得到有效的使用,他們只能讓你編寫糟糕的(效率低下,難以理解或維護)代碼。 – Roland
感謝您的回答。但不幸的是,我必須使用它們才能將值分配給我以前未創建的對象。因此,據我所知,這是創建一個嵌套循環的唯一方法,正如我在文章中提到的。 –
你不必,你不應該。使用一個列表。 – Roland