我创建了以下功能
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中更大的样本大小。
提前谢谢
答案 0 :(得分:2)
在一个匹配输入/输出的函数下面。基本上,它循环遍历数组的每个值,并从输入中派生新值。
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