[英]how to create n vectors in R
I'd like to create n vectors with the corresponding names.我想创建 n 个具有相应名称的向量。 For example: n<-1:10 And I need to create the corresponding vectors x_1, x_2, ..., x_n.例如:n<-1:10 我需要创建相应的向量 x_1、x_2、...、x_n。 Is it possible to do it with "for" loop or whatever else?是否可以使用“for”循环或其他方式来完成? For example:例如:
n=1:10
for (i in n) {
paste("x",n[i]) <- 1:9
}
The example doesn't work, but that's what I'd need to get.该示例不起作用,但这就是我需要得到的。 Thank you for your suggestions!谢谢您的建议!
Try this with the understanding that it may cause more problems than you realize:尝试这样做可能会导致比您意识到的更多的问题:
ls()
# character(0)
Vars <- paste("x", 1:10, sep="_")
Vars
# [1] "x_1" "x_2" "x_3" "x_4" "x_5" "x_6" "x_7" "x_8" "x_9" "x_10"
x <- sapply(Vars, assign, value=1:9, envir=environment())
ls()
# [1] "Vars" "x" "x_1" "x_10" "x_2" "x_3" "x_4" "x_5" "x_6" "x_7" "x_8" "x_9"
It is preferable to create the vectors within a list structure (data frame or list):最好在列表结构(数据框或列表)中创建向量:
X <- replicate(10, list(1:9))
names(X) <- Vars
str(X)
# List of 10
# $ x_1 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_2 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_3 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_4 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_5 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_6 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_7 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_8 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_9 : int [1:9] 1 2 3 4 5 6 7 8 9
# $ x_10: int [1:9] 1 2 3 4 5 6 7 8 9
The lapply()
and sapply()
functions make it easy to apply a function to all of the list parts with a single line of code. lapply()
和sapply()
函数可以轻松地使用一行代码将 function 应用于所有列表部分。 You can access the first list item with X[[1]]
or X[["x_1"]]
.您可以使用X[[1]]
或X[["x_1"]]
访问第一个列表项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.