在一个for循环中创建多个矩阵
我是R新手,目前正在学习创建for循环 我想做的是创建6个矩阵,它们具有类似的结构,唯一的区别是a行随矩阵的数量而变化:在一个for循环中创建多个矩阵,r,for-loop,matrix,dataframe,R,For Loop,Matrix,Dataframe,我是R新手,目前正在学习创建for循环 我想做的是创建6个矩阵,它们具有类似的结构,唯一的区别是a行随矩阵的数量而变化: matrix1<- matrix(nrow=5, ncol=5, dimnames= list(c("a", "b", "c", "d", "e") for(i in 1:5){ matrix1[1,]= 1 matrix1[2,]= round(rpois(5,1), digits=0) matrix1[3,]= round(rpois(5,1), digits=
matrix1<- matrix(nrow=5, ncol=5, dimnames= list(c("a", "b", "c", "d", "e")
for(i in 1:5){
matrix1[1,]= 1
matrix1[2,]= round(rpois(5,1), digits=0)
matrix1[3,]= round(rpois(5,1), digits= 0)
matrix1[4,]= round(rnorm(5, 50, 25), digits= 0)
matrix1[5,]= round(rnorm(5, 50, 25), digits= 0)
}
是否有任何有效的方法使用for循环而不是单独执行此操作
我还考虑过创建6个5*5矩阵,填充NA值,然后再填充所需的值,但我不知道怎么做
如果你能帮助我,那将是非常好的!
谢谢 不需要for循环,代码运行时不需要它。在R中,for循环允许您使用一个临时对象,在您的示例中,每个循环从1到5乘1进行迭代。为了利用循环,您需要使用i。您当前的for循环实际上只覆盖了自身5次 下面是一个在列表中创建6个矩阵的循环。这里的技巧是,我不仅使用I在列表中创建一个新元素a矩阵,而且还将第一行设置为随它所在的数字矩阵而变化
# First it is good to initialize an object that you will iterate over
lists <- vector("list", 6) # initialize to save time
for(i in 1:6){
# create a new matrix and set all values in it to be i
lists[[i]] <- matrix(i, nrow = 5, ncol = 5, dimnames= list(c("a", "b", "c", "d", "e")
))
# change the remaining rows
lists[[i]]["b",] <- round(rpois(5,1), digits = 0)
lists[[i]]["c",] <- round(rpois(5,1), digits = 0)
lists[[i]]["d",] <- round(rnorm(5, 50, 25), digits= 0)
lists[[i]]["e",] <- round(rnorm(5, 50, 25), digits= 0)
}
# Properly name your lists
names(lists) <- paste0("Matrix",1:6)
# Now you can call the lists individually with
lists$Matrix1
# Or send them all to your environment with
list2env(lists, env = .GlobalEnv)
让我知道这是否有帮助,或者如果你还有其他问题~写一个x的函数来生成矩阵,然后用lapplyvalues来表示x,有趣吗?请注意,有一个矩阵列表比在名称中嵌入矩阵号更好,比如matrix1、matrix2……但是我如何编写这个函数呢?你能给我举个例子吗?很有趣