0

I'm still relatively new to R, and am struggling to (A) build a rolling function, and (B) apply that function to an entire data frame.

The following equation is what I'm trying to calculate for my data.frame:

DSCOREx  =  {[(BAIX-3 + BAIX-2 + BAIX-1)/3] - [(BAIX + BAIX+1 + BAIX+2)/3]}        
/ {√STDX * √(2/3)}

Where "BAI X-n" = the value in every cell for X-n year.
Example: "BAI X-1" = the BAI value for the year prior to X year.

Here is a sample data.frame:

Year <- c(2000:2015)    
S1 <- c(10,14,12,9,6,14,7,12,11,8,9,15,9,10,7,11)    
S2 <- c(5,8,9,14,12,10,8,7,11,9,14,8,11,10,6,9)    
S3 <- c(12,13,9,8,11,7,10,9,11,14,8,6,10,9,12,14)    
df <- rbind(Year, S1, S2, S3)    
colnames(df) <- df[1,]    
df <- df[-1,]    

Basically I'd like to apply the equation to every annual value (which is BAI) for each sample (S1-S3), and the output would be a new dataframe with a DSCORE for each year, for each sample.

I've never written a function or applied it to a data.frame, so I started by just trying to put the equation in function form:

STDx <- function (x) {(((((x-3)-((x-3 + x-2 + x-1)/3))^2)+(((x-2)-((x-3 + x-2 + x-1)/3))^2)+(((x-1)-((x-3 + x-2 + x-1)/3))^2))+((((x)-((x + x+1 + x+2)/3))^2)+(((x+1)-((x + x+1 + x+2)/3))^2)+(((x+2)-((x + x+1 + x+2)/3))^2)))/2}    
DSCOREx <- function(x) {(((x-3 + x-2 + x-1)/3) - ((x + x+1 + x+2)/3)) / ((sqrt(STDx)) * (sqrt(2/3)))}

Now I have no idea what to do next to apply the functions to my data.frame (or if they're written correctly!). Any suggestions on how to apply the function to my data.frame would be appreciated. Thanks.

KKL234
  • 367
  • 1
  • 5
  • 23

1 Answers1

0

Your question is not entirely clear to me. You should define what X, n and STDX are. But perhaps this is what you're looking for.

DSCOREx <- matrix(0,nrow=nrow(df), ncol = ncol(df))
colnames(DSCOREx) <- colnames(df)
rownames(DSCOREx) <- rownames(df)

for (i in seq(1,nrow(df))){
   for (j in seq(4,(ncol(df)-3))){
      DSCOREx[i,j] <- (df[i,j-3] + df[i,j-2] + df[i,j-1] - df[i,j+1] - df[i,j+2] - df[i,j+3])/3
   }
}

I have not included the denominator.

slabofguinness
  • 773
  • 1
  • 9
  • 19