【问题标题】:Writing a function that depends on previous values of itself编写一个依赖于自身先前值的函数
【发布时间】:2017-07-25 03:14:59
【问题描述】:

我已经创建了以下函数

numberstocks <- function (x)
sapply (seq_along(x), function(i) {
    for (i in 1) {
    ifelse (x[i]==0,0,ifelse(x[i]==-1,100,ifelse(x[i]==1,0,0)))
    }
    for (i in 2:10){
    ifelse (x[i]==0, ifelse(is.numeric(numberstocks(x[i-1]))>-1,numberstocks(x[i-1]),0),ifelse(x[i]==0,0,ifelse(x[i]==-1,100,ifelse(x[i]==1,-1*is.numeric(numberstocks(x[i-1])),0))))
}
})

我的数据如下所示:

AAPL <- c(1,0,0,-1,0,1,0,0,0,-1)
MSFT <- c(0,0,0,1,0,-1,0,1,-1,0)

df <- data.frame (AAPL,MSFT)

我想将该函数应用于我的数据框

df.new <- as.data.frame (lapply(df,numberstocks))

期望的输出是:

AAPL.new <- (100,100,100,-100,0,100,100,100,100,-100)
MSFT.new <- (0,0,0,100,100,-100,0,100,-100,0)

但是,它说“具有 0 列和 0 行的数据框”,我不明白为什么。有人能找出我做错了什么吗?

我是一个初学者,从 Excel 中的小样本量转向 R 中的大样本量。

提前谢谢你

【问题讨论】:

  • 如果没有可重现的示例,我无法确定,但我怀疑您应该使用 if 和 else 而不是 ifelse。
  • 我不明白代码,您使用 sapply 和 i 的功能,但随后使用 for 循环也与 i.. 你能提供一个可重现的例子吗?
  • @Roland,如果不清楚,抱歉。我添加了一个可重现的示例和相应的错误
  • @Vandenman,如果不清楚,抱歉。我添加了一个可重现的示例。正如我在帖子中提到的,我是一个初学者。因此,由于使用 sapply 和循环,该函数可能是错误的。我该如何克服呢?
  • 别担心,开始总是很困难的。但是,我仍然不明白所需的输出是什么。你也可以提供吗?

标签: r function if-statement


【解决方案1】:

在与您的输入/输出相匹配的函数下方。基本上,它遍历数组的每个值并从输入中导出新值。

AAPL <- c(1,0,0,-1,0,1,0,0,0,-1)
AAPL.new <- c(100,100,100,-100,0,100,100,100,100,-100)

foo <- function(x) {

    newValue <- 0

    for (i in 1:length(x)) {

        if (x[i] == -1) {
            newValue <- -100
        } else if (x[i] == 1) {
            newValue <- 100
        } else if (x[i] == 0 && newValue != 100) {
            newValue <- 0
        }

        x[i] <- newValue

    }

    return(x)

}

# check whether the results match
foo(AAPL) == AAPL.new

AAPL <- c(1,0,0,-1,0,1,0,0,0,-1)
MSFT <- c(0,0,0,1,0,-1,0,1,-1,0)
df <- data.frame (AAPL,MSFT)

# now use sapply to execute the function on every column
sapply(df, foo) 

MSFT.new <- c(0,0,0,100,100,-100,0,100,-100,0)
df.new <- data.frame(AAPL.new, MSFT.new)

# check whether the results match
as.data.frame(sapply(df, foo)) == df.new

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2021-05-04
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多