r - Applying functions to vector elements to make rows in a new dataframe -
i've got interesting problem , have no idea begin -- in fact, wasn't sure how title question! want apply functions elements of dataframe , use these make new rows in new dataframe. example, suppose have dataframe df1
gives x
, y
data various state
s:
df1 <- data.frame(state=c("al","ak"), x=c(1,3), y=c(2,4))
what start first state al
, , make new dataframe df2
with 3 rows, new values of df2$x
calculated using 3 different functions give, example: df1$x
, df1$x - 1
, , df1$x + 1
. likewise, want similar thing new values of df2$y
, in example calculated df1$y
, df1$y * 0.5
, , df1$y * 0.5
.
then, proceed next state
. end result should be:
df2 <- data.frame(state=c("al", "al","al","ak","ak","ak"), x=c(1,0,2,3,2,4), y=c(2,1,1,4,2,2))
does know how might approach this? have no idea begin... can imagine kind of loop, i'm hoping there's more elegant approach in r.
base r solution:
funcs.x <- list(function(x) x, function(x) x-1, function(x) x+1) funcs.y <- list(function(y) y, function(y) y*0.5, function(y) y*0.5) apply.funcs <- function(funcs,x) as.vector(t(sapply(funcs, function(f) f(x)))) d <- data.frame(state = rep(df1$state,each=length(funcs.x)), x = apply.funcs(funcs.x, df1$x), y = apply.funcs(funcs.y, df1$y) ) identical(d,df2) # [1] true
Comments
Post a Comment