R Question

Writing a function that depends on previous values of itself

I have created the following function

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))))
}
})


My data looks something like this:

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)


And I want to apply the function to my data frame

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


The desired output would be:

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


However, it says "data frame with 0 columns and 0 rows" and I do not understand why. Could someone identify what I am doing wrong?

I am a begginer moving from small sample sizes in Excel to larger sample sizes in R.

Thank you in advance

Answer Source

Below a function that matches for your input/ output. Basically, it, loops through every value of the array and derives the new value from the input.

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download