Monday, 15 August 2011

r - Applying functions to vector elements to make rows in a new dataframe -


I have an interesting problem and I do not know where it is starting - in fact, I did not even know it That's how to the title of the question! What I want to do is apply the functions to elements of a dataframe and they are used to create new rows in the new dataframe. For example, suppose we have a dataframe df1 that is different for some X and y for various state S:

  df1 < - data.frame (state = C ("AL", "AK"), X = C (1,3), y = c (2,4))  

What do I do First, start with the state AL , and create a new dataframe df2 with 3 rows, where is new: For example: df1 $ X < Is calculated using 3 different functions for the value of / code>, df1 $ X - 1 , and df2 $ X , code> DF1 $ X + 1 . Similarly, I want to do the same thing for new values ​​of df2 $ Y , which in this example would be df1 $ Y , df1 $ Y * 0.5 Is calculated as , and df1 $ Y * 0.5 .

Then, I will go to the next state . The end result should be:

  df2 & lt; - 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 anyone know how I can approach this? I do not know that even to start ... I can imagine some kind of loop, but I hope there is a more elegant attitude in R.

base r solution:

  funcs.x and lt; - List (function (x) x, function (x) x-1, function (x) x + 1) funcs.y & lt; - list (function (y) y, function (y) y * 0.5, function (y) y * 0.5) apply.funcs & lt; - Function (funcs, x) as vector (T (sapply (funcs, function (f) f)) D & LT; - data.frame (state = delegate (df 1 $ state, each = length (funcs.x)), x = apply. (Funcs.X, df1 $ X), y = apply.funcs (funcs.y, Df1 $ y)) same (d, df2) # [1] TRUE  

No comments:

Post a Comment