Toolbox
Toolbox

Reputation: 2473

Construct variable name using a for-loop

I need to construct a set of variables where the variables should be constructed based on 2 parts: a) name b) a number that is stepped up with value [1]. For the increasing number i use a for-loop. I manage to create a string see test1, but not the increase the variable name, see test2.

Given the error code provided below I assume R does not want me to construct something using "paste0" that is part of the variable name.

My R-code:

numbers_for_variable_name <- c(1,2,3)

# Test-1 [works]
# Construct string with increasing number.
for (i in numbers_for_variable_name) {
    cat(paste0("number-", i, "\n"))
}
# Test-2 [does not work]
# Construct variable name with increasing number.
for (i in numbers_for_variable_name) {
    paste0("number-", i) <- "p1"
}

Outcome for "test1":

number-1
number-2
number-3

The error I get for test2 is:

Error in paste0("number-", i) <- "p1" : 
  target of assignment expands to non-language object

The expected outcome of "test2" is:

number-1 <- "p1"
number-2 <- "p1"
number-3 <- "p1"

Upvotes: 0

Views: 148

Answers (2)

akrun
akrun

Reputation: 886948

For the OP's code to work, it should be assign to assign an identifier for the value

for (i in numbers_for_variable_name) {
   assign(paste0("number-", i),  "p1")
 }

Note that identifiers with - are not standard, but _ is okay. So, if we wanted to get the value, use backquotes

`number-1`
#[1] "p1"

`number-2`
#[1] "p1"

However, it is not advisable to have multiple objects in the global environment.

Upvotes: 2

Roman Luštrik
Roman Luštrik

Reputation: 70623

You should use a structure that comes shipped with R - a list. You can name it, easily subset it or apply functions to it using lapply or lapply (or just loop through).

numbers_for_variable_name <- c(1,2,3)

myresult <- vector("list", length = length(numbers_for_variable_name))
names(myresult) <- paste("number-", numbers_for_variable_name, sep = "")

for (i in numbers_for_variable_name) {
  myresult[[i]] <- i
}

> myresult
$`number-1`
[1] 1

$`number-2`
[1] 2

$`number-3`
[1] 3

Subsetting:

> myresult[["number-3"]]
[1] 3

Applying a function to all list elements:

> lapply(myresult, FUN = function(x) x^2)
$`number-1`
[1] 1

$`number-2`
[1] 4

$`number-3`
[1] 9

Upvotes: 3

Related Questions