[R] for loop

Joshua Wiley jwiley.psych at gmail.com
Fri Oct 15 00:50:57 CEST 2010


If unlisting was the only issue, then this should also work, and will
save you the trouble of initializing a matrix, creating x, and using a
for loop.

## Brian's Function
f <- function(x) {
       r <- as.list(rnorm(6))
       names(r) <- paste("T",1:6,sep="")
       r
}

sapply(seq(0,1, by=0.1), function(x) {unlist(f(x))})

Cheers,

Josh

On Thu, Oct 14, 2010 at 3:43 PM, li li <hannah.hlx at gmail.com> wrote:
> Thanks for the kind help!
>               Hannah
>
> 2010/10/14 Brian Diggs <diggsb at ohsu.edu>
>
>>  On 10/14/2010 2:53 PM, li li wrote:
>>
>>> Dear all,
>>>   I have a function f(x)  which return a list as result.
>>>
>>> $T1
>>> [1] 0.03376190
>>> $T2
>>> [1] 0.04725
>>> $T3
>>> [1] 0.3796071
>>> $T4
>>> [1] 0.3713452
>>> $T5
>>> [1] 0.4523651
>>> $T6
>>> [1] 0.4575873
>>>
>>>   I now find the result for a vector of x values at one time. I want to
>>> store the reuslt
>>> for each xi value in a column of a matrix
>>>
>>> x<- seq(0,1, by=0.1)
>>> result<- matrix(0, nrow=6, ncol=length(x))
>>>
>>> for (i in 1:length(x)){result[,i]<- f(x[i])}
>>>
>>> It is not working. Can some help me.
>>> Thank you very much!
>>>                         Hannah
>>>
>>
>> In order to test my solution, I needed a function that returned something
>> of the structure you had.
>>
>> f <- function(x) {
>>        r <- as.list(rnorm(6))
>>        names(r) <- paste("T",1:6,sep="")
>>        r
>> }
>>
>> Using that, you can replace the for loop with:
>>
>> for (i in 1:length(x)){result[,i] <- unlist(f(x[i]))}
>>
>> The problem is that f returns a list; you can only put a vector in part of
>> a matrix.  unlist() takes care of that conversion.
>>
>> --
>> Brian S. Diggs, PhD
>> Senior Research Associate, Department of Surgery
>> Oregon Health & Science University
>>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list