[R] Applying a function to a dataframe

David Winsemius dwinsemius at comcast.net
Wed Dec 17 00:22:48 CET 2008


On Dec 16, 2008, at 6:00 PM, glenn roberts wrote:

> Another Newbie Question sorry:
>
> I am trying to apply a function a dataframe and could use some help:
>
>
> Assuming, dim(df) = (10,2) say, I would like to apply a function  
> that looks
> at each row in turn and returns a list (dim =(10,1)) using the  
> columns as
> inputs to the function, but with no INDEX stuff that the by() function
> refers to.
>
> For a simple function x+y I know in Mathematica it would be this;
>
> Table[df[[i,1]]+ df[[i,2]],{i,1,10}]
>
> Of if the function was defined is would read;
>
> Table[f[df[[i,1]], df[[i,2]]],{i,1,10}]

I don't know Mathematica, but if you just want the sum by rows

?apply

When the second argument is 1 the rows are taken singly as arguments  
to the third argument FUN:

 > DF <- data.frame(col1 = 1:10, col2 = 11:20)
 > apply(DF,1,sum)
  [1] 12 14 16 18 20 22 24 26 28 30


If you want minimums then the apply method  with FUN=min would still  
work:

 > apply(DF,1,min)
  [1]  1  2  3  4  5  6  7  8  9 10


>
>
> Thanks for help in advance
>
> Glenn
>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list