Suppose that I have assigned a set of matrices through the following for-loop.
for(i in 1:6){
stringname<-sprintf("%s_%s","MyName",i)
assign(paste(stringname),matrix(data=100,nrow=100,ncol=100)) #Should yield 6 arrays (MyName_1,MyName_2,...,MyName_6)
}
Suppose I want to assign 6 vectors that read in the first row of each of MyName_1 to MyName_6. How can this be accomplished? In other words, how do I select the first row of such an array based on a specified string (e.g., "MyName") and then assign the first row to a new variable?
Sorry for the inconveniences and troubles regarding this. Thanks for all the help over this!
Uncertain if this captures your intent
# example doesn't need to be so large
for(i in 1:6){
stringname<-sprintf("%s_%s","MyName",i)
assign(paste(stringname),matrix(data=10,nrow=10,ncol=10)) #Should yield 6 arrays (MyName_1,MyName_2,...,MyName_6)
} -> a
colnames(a)
#> NULL
labs <- letters[1:10]
labs
#> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
colnames(a) <- labs
a
#> a b c d e f g h i j
#> [1,] 10 10 10 10 10 10 10 10 10 10
#> [2,] 10 10 10 10 10 10 10 10 10 10
#> [3,] 10 10 10 10 10 10 10 10 10 10
#> [4,] 10 10 10 10 10 10 10 10 10 10
#> [5,] 10 10 10 10 10 10 10 10 10 10
#> [6,] 10 10 10 10 10 10 10 10 10 10
#> [7,] 10 10 10 10 10 10 10 10 10 10
#> [8,] 10 10 10 10 10 10 10 10 10 10
#> [9,] 10 10 10 10 10 10 10 10 10 10
#> [10,] 10 10 10 10 10 10 10 10 10 10
Created on 2020-09-30 by the reprex package (v0.3.0.9001)
FJCC
October 1, 2020, 12:00am
3
I understood the question differently, though I am also unsure I really got it right.
for(i in 1:6){
stringname<-sprintf("%s_%s","MyName",i)
assign(paste(stringname),matrix(data=100*i,nrow=100,ncol=100)) #Should yield 6 arrays (MyName_1,MyName_2,...,MyName_6)
}
VectorNames <- paste0("V", 1:6)
for (i in 1:6){
assign(VectorNames[i], get(paste0("MyName_", i))[1, ])
}
1 Like
system
Closed
October 22, 2020, 12:00am
4
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.