[R] How to perform arithmetic across rows

Joshua Wiley jwiley.psych at gmail.com
Thu Oct 28 22:31:41 CEST 2010


Hi Nick,

Take a look at ?cbind and ?"["

Here is some (untested) code that is how I might go about it.  It
takes advantage of the fact that a single value will be recycled to
equal the necessary length.  Then I just assign over the NA in row 24.

myframe <- cbind(myframe, New = NA)
myframe[24, "New"] <- with(myframe, A[1] - A[24])

New will be an all NA column except for row 24.

Cheers,

Josh

On Thu, Oct 28, 2010 at 11:47 AM, Nick Ackerman <nick.ackerman at pgn.com> wrote:
>
> Hi All,
>
> I have a data frame (myframe) with variables (columns) A,B,C and 100 records
> (rows) for each. Column A is numeric. I would like to append a column to
> myframe that subtracts the value in row 24 of A from row 1 of A. In this
> procedure the first 23 rows of the new column will necessarily be blank
> (NA). Can anyone provide guidance for me here?
>
> Thanks in advance for your time.
>
> Nick
> --
> View this message in context: http://r.789695.n4.nabble.com/How-to-perform-arithmetic-across-rows-tp3017905p3017905.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list