Reputation: 181
I'm new to R and I'm trying to create a loop in R with a string mod
and a variable x
my code so far looks like this m=1
and b=1
at the start of the code
for (i in 1:5){
mod = 'mod'
mod + as.character(m) = b
m = as.numeric(m)
m = m+1
b = (b + 1) * 2
}
what I want as an output is:
mod1 = 1
mod2 = 4
mod3 = 10
Is this possible or am I overthinking this problem?
Upvotes: 0
Views: 37
Reputation: 5017
You can assign values to a variable with incrementing id using assign(paste("mod",m,sep=""), b)
Your loop could be something like this:
for (i in 1:5){
assign(paste("mod",m,sep=""), b)
m = m+1
b = (b + 1) * 2
}
You can find these variables in memory, as the loop is closed:
> mod1
[1] 1
> mod2
[1] 4
> mod3
[1] 10
> mod4
[1] 22
> mod5
[1] 46
> mod6
[1] 94
Upvotes: 1
Reputation: 10375
Save the results in a list, use list2env
m=1
b=1
res=list()
for (i in 1:5){
mod = 'mod'
res[[paste0(mod,as.character(m))]] = b
m = as.numeric(m)
m = m+1
b = (b + 1) * 2
}
list2env(res,envir = .GlobalEnv)
Upvotes: 0