0

I am new to R

I have a data frame STAT.VECTORS with two columns A and B. I need to add column C to STAT.VECTORS such that C[i] = func( A[i] , B[i] )

What is the most syntactically efficient way to do this in R?

Any way to extend the solution such that C[i] = func( A[i-1] , B[i-2] )

Having a developer background, I would create a loop and assign values to C. I expect better from R:)

UPDATE

The following example should elaborate my question. The loop picks specific elements relative to the current row and hand them to a function.

Can I do the loop logic below without loop by using apply family?

l=50

func=function(x,y){return(y-x)}

a=sample(1:6,l,replace = T)
b=sample(1:6,l,replace = T)
c=sample(1:6,l,replace = T)
d=sample(1:6,l,replace = T)
e=sample(1:6,l,replace = T)
f=vector("numeric",l)
test.data = cbind(a,b,c,d,e,f)

for(i in 2:l)
{
  test.data[i,"f"]= func(test.data[i,"d"],test.data[i-1,"b"])
}
test.data
Allan Xu
  • 7,998
  • 11
  • 51
  • 122
  • Basically you need to look into the [apply family](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega) functions – Sotos Apr 08 '16 at 13:39
  • @Sotos: I can't find a way to use handle my requirement with the apply family function. The function apply does not let me choose which exact element index become the function parameter. In my case f(a,b) != f(b,a) see my reply to TheRimalaya – Allan Xu Apr 08 '16 at 14:37
  • Maybe if you create separate vectors with required indexes and use them in your `apply` functions. We can't help you any further though unless you provide detailed and specific examples of your problem. – Sotos Apr 08 '16 at 14:49
  • Take a look at [this link](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and revise your question – Sotos Apr 08 '16 at 14:56
  • @TheRimalaya : I added the code that represents the idea. – Allan Xu Apr 08 '16 at 18:32

1 Answers1

0

I created a data.frame as,

dfx <- data.frame(a = sample(15), b = sample(15))

dfx$c <- apply(dfx, 1, sum)

This will add a column c with sum of a and b. instead of sum you can put any function that will take a range of value and has single output.

dfx$c <- apply(dfx, 1, <some fun>)
TheRimalaya
  • 4,232
  • 2
  • 31
  • 37
  • The function sum is not a good representative of my function. My function does not take a range and f(a,b) != f(b,a). I do need to have control on the parameters. Do we have such capability with apply? – Allan Xu Apr 08 '16 at 14:34
  • You have to give some more hind on about your function, otherwise, it will be difficult to help you – TheRimalaya Apr 08 '16 at 14:55