[R] making operators act on rows of a data frame

Tom Blackwell tblackw at umich.edu
Thu Mar 11 16:26:26 CET 2004


Jonathan  -

Petr Pikal suggests  RowSums()  for your specific task.

A more general solution is given by  apply()  and  sapply().
These functions will apply any R function (even one that you
would write yourself) to individual members of any dimension
of an array, matrix or data frame, or any combination of
dimensions (in the context of a three or four-dimensional
[or more] array).  See  help("apply"), help("sapply").

-  tom blackwell  -  u michigan medical school  -  ann arbor  -

On Thu, 11 Mar 2004, Jonathan Williams wrote:

> Dear R helpers,
> I wish to use the "sum" operator for each row of a data frame.
> However, it appears that the operator acts on the entire data
> frame, over all columns. What is the best way to obtain row-
> wise operation?
>
> The following code shows my attempts so far, and their problems:-
>
> test1=array(rbinom(120,1,0.5),c(20,3))
> test1[,3]=NA
> sum(test1[,1:2])
> test1[,3][sum(test1[,1:2])>=2]=1
> test1[,3][sum(test1[,1:2])]
> test1
>
> test2=array(rbinom(120,1,0.5),c(20,3))
> test2[,3]=NA
> sum(test2[,1:2])
> test2[,3][(test2[,1]+test2[,2])>=2]=1
> test2[,3][sum(test2[,1:2])]
> test2
>
> In the 1st section, I try to use "sum" to add the first two columns
> of a data frame. Here, sum(test1[,1:2]) evaluates to a single integer
> but this modifies *all* the rows of test1.
>
> In the 2nd section, specifying addition of the first two columns with
> a '+' acts row-by row, as I want. This is OK for this demonstration,
> but would be impractical in the program I am trying to write (where
> the columns I wish to sum are numerous and change from time to time).
>
> I would be very grateful to know if it is possible to get operators
> to act on rows of a data frame, and if so, how.
>
> I am running R1.8.1 on Windows NT.
>
> Jonathan Williams
> OPTIMA
> Radcliffe Infirmary
> Woodstock Road
> OXFORD OX2 6HE
> Tel +1865 (2)24356
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list