【问题标题】:R: for loop outputR:for循环输出
【发布时间】:2016-03-16 11:16:24
【问题描述】:

我有两个数据集

    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)

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

【问题讨论】:

  • 您的代码不可重现。你参考data4。我假设您的意思是data1。你引用idealized.ranks2,你没有提供。
  • 感谢您的反馈,@Jean V. Adams,我更正了。
  • 我为逐渐更正而道歉。提到的丢失或错误的向量/名称存储在我的工作区中,这就是为什么我倾向于忘记一些细节。
  • 这是一个容易犯的错误。最好的办法是尝试在“vanilla”R 会话中运行代码,不加载任何对象或库。

标签: r for-loop output


【解决方案1】:

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

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

【讨论】:

  • 谢谢@Jean V. Adams,你的方法给了我想要的东西。最后,我只是根据自己的需要修改了结果列表。
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 2018-12-17
相关资源
最近更新 更多