Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

for loop with "<-" to create variables in R

So I have this data :

data<-as.data.frame(matrix(1:9,ncol=3))

which gives this :

| V1 | V2 | V3 |  
________________  
|  1 | 2  | 3  | 
|  4 | 5  | 6  |
|  7 | 8  | 9  |

I want to create a variable for each column to get this :

> V1
[1] 1 2 3

> V2
[1] 4 5 6

> V3
[1] 7 8 9

I know that if I do a loop with the assign function :

for (i in 1:length(data)) {
               assign(names(data[i]),data[,i])
               
}

it works. But if I try with the "<-" :

for (i in 1:length(data)) {
           names(data[i])<-data[,i]
           
}

it does not work. Why does it work with the assign function but not with the "<-" ?

question from:https://stackoverflow.com/questions/65876320/for-loop-with-to-create-variables-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use list2env

list2env(data, .GlobalEnv)

-check for objects

V1
#[1] 1 2 3
V2
#[1] 4 5 6
V3
#[1] 7 8 9

In the for loop, it can be looped over the column names and use assign

for(nm in names(data)) assign(nm, data[[nm]])

The names assignment works only for assigning the column names or names attribute of a vector and not create an object. The error is basically about the difference in length of the lhs and rhs of the assignment (<-) operator

names(data[1])
#[1] "V1"

Better would be

names(data)[1]

and

data[,1]
#[1] 1 2 3

is the value of the column which is of length 3

when we assign <-) it to the names(data)[1], it is assigning the first column name to 1 2 3 which differs in length

names(data)[1] <- data[,1]

Warning message: In names(data)[1] <- data[, 1] : number of items to replace is not a multiple of replacement length

returns a warning, but if we use the OP's method of subsetting

names(data[1]) <- data[,1]

Error in names(data[1]) <- data[, 1] : 'names' attribute [3] must be the same length as the vector [1]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...