[R] help

Steven McKinney smckinney at bccrc.ca
Fri Oct 15 04:55:17 CEST 2010


Here's one way to do it:

Use unlist() to change the function's output from a list to a vector.

> f <- function(x) {return(lapply(1:6, function(z) z + x))}
> f(2)
[[1]]
[1] 3

[[2]]
[1] 4

[[3]]
[1] 5

[[4]]
[1] 6

[[5]]
[1] 7

[[6]]
[1] 8

> x <- seq(0,1, by=0.1)
> result <- matrix(0, nrow=6, ncol=length(x))
> for (i in 1:length(x)){result[,i] <- unlist(f(x[i]))}
> result
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,]    1  1.1  1.2  1.3  1.4  1.5  1.6  1.7  1.8   1.9     2
[2,]    2  2.1  2.2  2.3  2.4  2.5  2.6  2.7  2.8   2.9     3
[3,]    3  3.1  3.2  3.3  3.4  3.5  3.6  3.7  3.8   3.9     4
[4,]    4  4.1  4.2  4.3  4.4  4.5  4.6  4.7  4.8   4.9     5
[5,]    5  5.1  5.2  5.3  5.4  5.5  5.6  5.7  5.8   5.9     6
[6,]    6  6.1  6.2  6.3  6.4  6.5  6.6  6.7  6.8   6.9     7
> 

HTH

Steven McKinney

________________________________________
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of li li [hannah.hlx at gmail.com]
Sent: October 14, 2010 2:50 PM
To: r-help
Subject: [R] help

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.

        [[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.



More information about the R-help mailing list