简体   繁体   中英

value name as string in assign function

I want to use different data frames in a loop. I am having trouble with accesing the different data frames within the loop.

Data1<-data.frame(X=rnorm(100,2), Y=rnorm(200,2), Z=rnorm(200,2))
Data2<-data.frame(X=rnorm(300,500), Y=rnorm(300,500))
Data3<-data.frame(X=rnorm(500,200), Y=rnorm(20,200))

for (i in c(1:3)){
assign("CurrentData", paste("Data", i, sep=""))
colMeans(CurrentData)
}

The assign function does not do what I want because it thinks the second argument is a string and not the name of an object. How can I get around this?

See ?assign

It's assign(x, value) where x is a variable name and value is an object to be assigned to that variable name

Currently, you have this:

...
assign("CurrentData", paste("Data", i, sep=""))
## This is equivalent to: CurrentData <- "Data1" 
... 

You are assigning CurrentData the string value : "Data1", "Data2", "Data3" but not the values of the objects of the same names themselves.

Try using ?get . Like so:

...
assign("CurrentData", get(paste("Data",i,sep="")))
...

BONUS:

You're better off with colMeans(x) for this purpose.

Your assign statement needs to be like this

assign("CurrentData", eval(as.name(paste("Data", i, sep="")))

The call to as.name converts the string to a symbol name, then the eval actually fetches the value of the symbol.

There are other ways to do it, but this clearly expresses the intent.

A simpler way to achieve what you want would be this

Data1<-data.frame(X=rnorm(100,2), Y=rnorm(200,2), Z=rnorm(200,2))
Data2<-data.frame(X=rnorm(300,500), Y=rnorm(300,500))
Data3<-data.frame(X=rnorm(500,200), Y=rnorm(20,200))

for (CurrentData in list(Data1, Data2, Data3)){
    somefunction(CurrentData)
}

Note I use a list to avoid all the data frames being coerced into one big vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM