[R] making operators act on rows of a data frame
Jonathan Williams
jonathan.williams at pharmacology.oxford.ac.uk
Thu Mar 11 13:13:56 CET 2004
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
More information about the R-help
mailing list