How to effectively divide the successor by the previous in each column of the data frame

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. , .

+4
2

base R:

myDF[,paste0(names(myDF), "mod")] <- sapply(myDF, function(x) c(NA, x[-1]/head(x,-1)))
#  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
+6

data.table ( GH)

library(data.table) ## V 1.9.5
setDT(myDF)[, paste0(names(myDF), "mod") := lapply(.SD, function(x) x/shift(x))]
#    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

dplyr, ( (?) mutate_each, )

library(dplyr)
myDF %>% 
  mutate_each(funs(./lag(.))) %>%
  cbind(myDF, .)
#   a         b        a        b
# 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
+7

Source: https://habr.com/ru/post/1605630/


All Articles