I am trying to assign a value to a concatenated variable name. This is an example of how it's done:
for(sector in 1:4) {
for(letter in 1:2) {
if (letter == 1) {
letter = 'V'
}
else if (letter == 2) {
letter = 'A'
}
print(paste(toString(sector), letter, "_variable", sep = ""))
paste(toString(sector), letter, "_variable", sep = "") <- sector
}
}
Basically what the outcome has to be: 8 variables (1V_variable, 1A_variable, 2V_variable, ...) with as value the sector (= number).
But I am getting the following error:
could not find function "paste<-"
Do you know any solution to solve this? Thanks in advance!
CodePudding user response:
I think you are looking for assign
-
for(sector in 1:4) {
for(letter in 1:2) {
if (letter == 1) {
letter = 'V'
}
else if (letter == 2) {
letter = 'A'
}
print(paste(toString(sector), letter, "_variable", sep = ""))
assign(paste(toString(sector), letter, "_variable", sep = ""), sector)
}
}
You need to use variable names with backticks to access them since it starts with a number.
`1V_variable`
#[1] 1
`1A_variable`
#[1] 1
A side note - It is not considered a good practice to create so many variables in global envoirnment try to use lists instead.
CodePudding user response:
Try this in the middle of your loop.
newvarname = paste(toString(sector), letter, "_variable", sep = "")
eval(parse(text = paste0(newvarname, " = sector")))