0

My little example is as follows:

x = c(5,1,3)
y = c(-1,3,1)
X = cbind(x,y)

I want to achieve

x1 = X[1,]
y1 = X[2,]
z1 = X[3,]

in a loop. Then I try

x = c(5,1,3)
y = c(-1,3,1)
X = cbind(x,y)
nr = nrow(X)
nc = ncol(X)
for(i in nr){
    k = length(letters)
    get(paste0(letters[k-(nr-i)],1)) = X[i,]
}

But I get a error as

Error in get(paste0(letters[k - (nr - i)], 1)) <- X[i, ] :
could not find function "get<-"

How can fix this issue?

1 Answer 1

3

You might be looking for assign instead of get. However, here is a way to do it without a loop.

list2env(setNames(asplit(X, 1), c('x1', 'y1', 'z1')), .GlobalEnv)

x1
# x  y 
# 5 -1 

y1
#x y 
#1 3 

z1
#x y 
#3 1 

Using assign :

x = c(5,1,3)
y = c(-1,3,1)
X = cbind(x,y)
nr = nrow(X)
nc = ncol(X)
k = length(letters)

for(i in 1:nr){
  assign(paste0(letters[k-(nr-i)],1), X[i,])
}
Sign up to request clarification or add additional context in comments.

2 Comments

Tks! It works! While, as you point out using assign, I change get(paste0(letters[k-(nr-i)],1)) = X[i,] as assign(paste0(letters[k-(nr-i)],1), X[i,]) in my original code, and it still fails @ronak-shah@Ronak Shah
Wow, gorgeous! That's I want. Tks!@ronak-shah@Ronak Shah

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.