具有不同数据帧大小的变量的函数

时间:2018-06-12 07:38:26

标签: r

所以我试图运行下面的功能,希望在输出中得到224个向量,但只得到一个,我不知道为什么。

ee <- 0.95
td <- 480

tt <- c(60,10,14,143,60)
tt <- as.data.frame(tt)

r <- vector()

m <- function(d)
{
    n <- length(tt)
    c <- nrow(d)
    for (j in 1:c)
{
    for (i in 1:n)
{
    r[i] <- tt[i]/(td*ee/d[j,])
}
    return(r)  
}

#where d is a data frame of 224 obs. of 1 variable

我得到的输出是

[[1]]
[1] 1026.3158  171.0526  239.4737 2446.0526 1026.3158

2 个答案:

答案 0 :(得分:1)

问题来自于这样一个事实:由于r放置在循环中,你的函数只返回计算的最后return向量。 一种方法是将结果存储在列表中:

r <- vector()

m_bis <- function(d) {

  res <- list() # store all the vectors here

  n <- length(tt)
  c <- nrow(d)

  for (j in 1:c) {
    for (i in 1:n) {
      r[i] <- tt[i] / (td * ee / d[j,])
    }
    res[j] <- r
  }  
  return(res)
}

这应该会产生这样的结果:

m_bis(as.data.frame(mtcars$mpg))
> [[1]]
  [1] 2.7631579 0.4605263 0.6447368 6.5855263 2.7631579
  ...
  [[32]]
  [1] 2.8157895 0.4692982 0.6570175 6.7109649 2.8157895

答案 1 :(得分:0)

java.io.FileNotFoundException: res\Worlds\world1.world (The system cannot find the path specified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileReader.<init>(Unknown Source)
        at dev.DualKeys.SIF.utils.Utils.loadFileAsString(Utils.java:13)
        at dev.DualKeys.SIF.worlds.World.loadWorld(World.java:47)
        at dev.DualKeys.SIF.worlds.World.<init>(World.java:18)
        at dev.DualKeys.SIF.states.GameState.<init>(GameState.java:24)
        at dev.DualKeys.SIF.Game.init(Game.java:56)
        at dev.DualKeys.SIF.Game.run(Game.java:86)
        at java.lang.Thread.run(Unknown Source)
java.lang.NumberFormatException: For input string: ""
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at dev.DualKeys.SIF.utils.Utils.parseInt(Utils.java:29)
        at dev.DualKeys.SIF.worlds.World.loadWorld(World.java:49)
        at dev.DualKeys.SIF.worlds.World.<init>(World.java:18)
        at dev.DualKeys.SIF.states.GameState.<init>(GameState.java:24)
        at dev.DualKeys.SIF.Game.init(Game.java:56)
        at dev.DualKeys.SIF.Game.run(Game.java:86)
        at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 1
        at dev.DualKeys.SIF.worlds.World.loadWorld(World.java:50)
        at dev.DualKeys.SIF.worlds.World.<init>(World.java:18)
        at dev.DualKeys.SIF.states.GameState.<init>(GameState.java:24)
        at dev.DualKeys.SIF.Game.init(Game.java:56)
        at dev.DualKeys.SIF.Game.run(Game.java:86)
        at java.lang.Thread.run(Unknown Source)

使用矢量化来加速计算。