开发者

Construct a loop over function, and apply does not work.

开发者 https://www.devze.com 2023-03-23 04:21 出处:网络
I\'m very new to R, I want to run a specific function (ideal from the pscl package) for 50 different data (roll call class) that have a suffix from 1 to 50, and I want to save the results in objects a

I'm very new to R, I want to run a specific function (ideal from the pscl package) for 50 different data (roll call class) that have a suffix from 1 to 50, and I want to save the results in objects also with a 1 to 50 suffix, but I can not do it.

The apply does not work, since I need to specify additional paramaters in the ideal function, and I already tried creating a new function that sets the additional parameters and permits to specify the function only with the data, but it fails in the second step (does not recognize the object).

I have the data objects for my function: rc.1, rc.2, ..., rc.50 And try to do the following - following closely how I would do it in Stata...

for开发者_StackOverflow中文版 (i in 1:3) {
    est.leg[i]<-ideal(rc[i], maxiter=1000, burnin=500, thin=10, normalize=TRUE)
}

And it does not evaluate in rc[i], says "object 'rc' not found"

I have also tried:

loop.ideal<- function(zz){ 
   ideal(zz, d=1, maxiter=100, burnin=50, thin=10, normalize=TRUE)
}

but when testing the function, it does not work with the iterations.

I would really appreciate any help!!!!


As Gavin says.

You can loop over the names of your objects, like :

object.names <- paste("rc",1:50,sep=".")

Better is to learn to work with lists. You can make a list of the objects by using lapply

object.list <- lapply(object.names,get)

This one will use the function get on every name on the list with names. lapply returns a list, so you have a list of the objects.

If the function is correct, you can then use the same trick again for the ideal function :

est.leg <- lapply(object.list,ideal , maxiter=1000, burnin=500, 
                  thin=10, normalize=TRUE)

This should give the correct solution.


You can pass extra arguments to apply(), see the ... argument in ?apply. If what you write is correct, you don't have objects rc[i], you have rc.i where i is actually an integer. [ is for subsetting an object, so your code is asking for the ith component of the rc object. You seem to be wanting to retrieve the object with name rc.i with i replaced by an integer.

Without knowing more about rc etc, you can try get(paste("rc.", i, sep = "")) in place of rc[i].

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号