I have dataframe myDFcreated like this:
a <- 1:4
b <- seq(3, 16, length=4)
myDF <- data.frame(a=a, b=b)
which is as follows:
a b
1 1 3.000000
2 2 7.333333
3 3 11.666667
4 4 16.000000
Now I want to separate subsequently the predecessor and successor in each column, add the results to the existing data frame, replace one missing value in each column with NAand add new column names. In the above example, my desired result is as follows:
a b amod bmod
1 1 3.000000 NA NA
2 2 7.333333 2.000000 2.444444
3 3 11.666667 1.500000 1.590909
4 4 16.000000 1.333333 1.371429
So, in column a2 is divided by 1, 3 is divided by 2, and 4 is divided by 3, and the results are stored in amod.
Now I do it like this:
divStuff <-function(aCol){
newCol <- aCol[2:length(aCol)]/aCol[1:length(aCol) - 1]
newCol <- c(NA, newCol)
return(newCol)
}
newDF <- data.frame(lapply(myDF, divStuff))
names(newDF) <- paste(names(myDF), "mod", sep="")
endDF <- cbind(myDF, newDF)
I wrote a function divStuffthat performs division and then calls lapply, which applies this function to each column of the data frame.
, , , , , cbind cbind , newCol <- c(NA, newCol), NA. , .