Markus
Markus

Reputation: 1

How to assign an object's value instead of the object's name

I have the folowing loop in R:

for (i in 1:length(M_names)) {
  for (j in 1:length(temp)) {

    q <- paste("M", j, "[", i, ",]", sep="")
    assign(M_names[[i]], q) 

  }
}

I want to create objects with the names stored in M_names and assign them length(temp) values from e.g. M1[1,]

My problem now is the following: The loop creates the objects I need with the correct names, but assign() does not instead the values of e.g. M1[1,] but this character string. So how do I chage this character string to the values behind it?

Next thing I want to do is to not overwrite the values with each j loop, but append them together but I will manage to do so later.

Maybe there is a much easier way without using loops but I am kind of new to R and loops seem familiar to me.

Thanks in advance and best regards, Markus

Upvotes: 0

Views: 730

Answers (1)

JJ Hendriks
JJ Hendriks

Reputation: 11

It seems as though you are searching for the eval() function instead of the assign() function. The eval() function, together with the parse() function, can execute text and return the output. Let's see a simple example:

x <- eval(parse(text = "1 + 1"))
print(x)

The value for x prints out as 2. I tried to work with your code to create a reproducable example:

M_names <- list(
  "M_name_1" = seq(1, 10),
  "M_name_2" = seq(1, 20),
  "M_name_3" = seq(1, 30)
)

temp <- list(
  "temp_name_1" = seq(10, 20),
  "temp_name_2" = seq(20, 30)
)

M1 <- data.frame(
  x = paste('m1', seq(1,3), sep = "_")
)

M2 <- data.frame(
  x = paste('m2', seq(1,3), sep = "_")
)
for (i in 1:length(M_names)) {
  M_names[[i]] <- vector("list", length(temp))
  for (j in 1:length(temp)) {
    q <- paste("M", j, "[", i, ",]", sep="")
    q_result <- eval(parse(text=q))
    print(q)
    print(q_result)
    M_names[[i]][[j]]<- eval(q_result)
  }
}

Upvotes: 1

Related Questions