R:用于循环输出

时间:2016-03-16 11:16:25

标签: r for-loop output

我有两个数据集

    data1 <- data.frame(c(0.0000, 0.5949, 0.8190, 1.0350, 
                          0.4960, 0.4000, 0.5000, 
                          0.3000, 0.4560, 0.6338, 1.2110 ),
                         c(0.0000, 0.8445,0.8900,1.1120,0.6780,
                           0.3000,0.5660,0.6000,0.8320,0.5987,1.1740 ))

vector1 <- list(rep(c(10,5,2), 5), rep(c(20,10,5), 5))

vector1是一个愚蠢的例子,但它保留了我的真实列表的结构)

    n2 <- 10
    idealized.ranks2 <- c(0:10)
    sorted.z <- NULL
    fonction <- list()
    n.2.bis <- NULL
    n.2.simu.bis <- NULL
    precip.back2 <- rep(list(as.vector(NULL)), 4)

for(z in 1:dim(data1)[2]){
  sorted.z[[z]] <- sort(data1[,z])
  fonction[[z]] <- approxfun(idealized.ranks2, sorted.z[[z]])

  for(x in 1:length(vector1)){
    n.2.bis[[x]] <- pnorm(vector1[[x]])
    n.2.simu.bis[[x]] <- n.2.bis[[x]]*(n2+1)

    precip.back2[[x]] <- fonction[[z]](n.2.simu.bis[[x]])
    print(z)
  }
}
[1] 1
[1] 1
[1] 2
[1] 2

输出结果显示fonction[[2]]vector1[[1]]以及fonction[[2]]vector1[[2]]的结果,因此precip.back2中的列表为2。 我想要的是precip.back2中的4个列表,其结果为:

fonction[[1]] and vector1[[1]], 
fonction[[1]] and vector1[[2]],
fonction[[2]] and vector1[[1]], 
fonction[[2]] and vector1[[2]]

就像在print(z)中一样。

你有什么建议吗? 最好的,

1 个答案:

答案 0 :(得分:0)

我不确定这是你所追求的,确切地说。但是,也许它会有所帮助。

data1 <- data.frame(
  c1=c(0.0000, 0.5949, 0.8190, 1.0350, 0.4960, 0.4000, 0.5000, 
    0.3000, 0.4560, 0.6338, 1.2110),
  c2=c(0.0000, 0.8445, 0.8900, 1.1120, 0.6780, 0.3000, 0.5660,
    0.6000, 0.8320, 0.5987, 1.1740))
vector1 <- list(rep(c(10, 5, 2), 5), rep(c(20, 10, 5), 5))
n2 <- 10
idealized.ranks2 <- c(0:10)

# define a data frame with all combinations of x and z
df <- expand.grid(xx=1:length(vector1), zz=1:dim(data1)[2])
# create an empty list for the results
results <- vector("list", dim(df)[1])
# run through your code for each combination of x and z
for(i in 1:dim(df)[1]) {
  x <- df$xx[i]
  z <- df$zz[i]
  sorted.z <- sort(data1[, z])
  fonction <- approxfun(idealized.ranks2, sorted.z)
  n.2.bis <- pnorm(vector1[[x]])
  n.2.simu.bis <- n.2.bis*(n2+1)
  precip.back2 <- fonction(n.2.simu.bis)
  # save the results
  results[[i]] <- list(x, z, sorted.z, fonction,
    n.2.bis, n.2.simu.bis, precip.back2)
}
# look at the results
results