DanielUp
DanielUp

Reputation: 23

New variable for loop in R

My problem is that I don't know how to create new variables using a for-loop.

Let's assume to have a matrix named X

x1 x2 x3
1  2  3
4  5  6
7  8  9

what I want to get is (it's easy but it's just an example)

v1=1
v2=5
v3=9

I want to use a for-loop like this one:

for (i in 1:3){
  v_i=X[i,i]
 }

But it doesn't work because I don't know how to create a new variable using the "i" index (v1,v2,v3,...).

Upvotes: 0

Views: 1166

Answers (3)

Vikram Venkat
Vikram Venkat

Reputation: 671

Assuming X is your dataframe name

for (i in 1:3) {
      assign(eval(paste0("v", i)), X[i,i])
   }

Upvotes: 0

JeremyS
JeremyS

Reputation: 3525

For loops execute in the global environment (functions create their own), So you need to make an object for the loop to update

MyNewX <- vector(mode="numeric",length=3)

Then have the loop update this object

for (i in 1:3){
  MyNewX[i] <- X[i,i]
}

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70653

You can use assign for this.

for (i in 1:3) {
  assign(sprintf("X_%s", i), i)
}

> ls()
[1] "i"   "X_1" "X_2" "X_3"

But I would be willing to bet my families farm that this is probably not what you're really after. A lot of things can be solved using a list, which come with already made tools to handle them (like lapply, sapply...).

Upvotes: 3

Related Questions