Возможно, вы захотите сравнить (микробенчмарк библиотеки cf) эти 3 решения, в зависимости от количества имеющихся у вас факторов и числовых переменных.
Использование базы R
n <- 3
set.seed(1)
dframe <- data.frame(Day = rep("Mon", n),
Time = 1:n,
Temper = round(rnorm(n, 4, 2), 0))
# --- convert factor to numeric
mframe <- as.data.frame(sapply(dframe, as.numeric))
# --- function to use on variables
pfun <- function(x, coef = 1/4){
# x <- mframe$Time ; coef <- .25 ;
newp <- x[1:(length(x)-1)] + diff(x, lag = 1) * coef
res <- c(rbind(x[1:(length(x) -1) ], newp) , x[length(x)] )
return( res )
}
# --- base R way
# pfun( mframe$Time )
# sapply(mframe, pfun, .5)
apply(mframe, 2, pfun)
dframe_final <- as.data.frame ( apply(mframe, 2, pfun) )
# str(dframe_final)
# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
dframe_final[[col]] <- factor(dframe_final[[col]])
levels( dframe_final[[col]] ) <- levels(dframe[[col]])
}
dplyr
# --- dplyr way
library(dplyr)
library(purrr)
lfactors <- dframe %>%
map_if(is.factor, levels)
dframe2 <- dframe %>%
as_tibble %>%
map_dfr(as.numeric) %>%
map_dfr(pfun) %>%
mutate_at(.vars = names(dframe)[sapply(dframe, is.factor)], .funs = factor)
# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
dframe2[[col]] <- factor(dframe2[[col]])
levels( dframe2[[col]] ) <- levels(dframe[[col]])
}
data.table
# --- data.table way
library(data.table)
dframe3 <- data.table(dframe)
dframe3 <- dframe3[ , lapply(.SD, as.numeric)]
dframe3 <- dframe3[ , lapply(.SD, pfun)]
# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
dframe3[ , (col) := factor(get(col)) ]
levels( dframe3[[col]] ) <- levels(dframe[[col]])
}