[R] rows process in DF
Phil Spector
spector at stat.berkeley.edu
Wed Jul 14 23:18:14 CEST 2010
If you don't mind avoiding a loop, here's one way to
solve your problem:
> myDF = data.frame(id=c(100,101),d1=c(.3,.3),d2=c(.4,.4),d3=c(-.2,.5),d4=c(-.3,.6),d5=c(.5,-.2),d6=c(.6,-.4),d7=c(-.9,-.5),d8=c(-.8,-.6))
> doit = function(x)c(x[1],sum_positive=sum(x[-1][x[-1]>0]),sum_negative=sum(x[-1][x[-1]<0]))
> t(apply(myDF,1,doit))
id sum_positive sum_negative
[1,] 100 1.8 -2.2
[2,] 101 1.8 -1.7
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Wed, 14 Jul 2010, jd6688 wrote:
>
> I have the following datasets:
>
> id d1 d2 d3 d4 d5 d6 d7 d8
> 1 100 0.3 0.4 -0.2 -0.3 0.5 0.6 -0.9 -0.8
> 2 101 0.3 0.4 0.5 0.6 -0.2 -0.4 -0.5 -0.6
>
> what I am trying to accomplish:
>
> loop through the rows && do the following:
> if the values from the columns of the current row >0 then
> sum_positive=total
> if the values from the columns of the current row <0 then
> sum_negtive=total
>
> then discard the columns and create a new table
>
>
> id sum_positive sum_negtive
>
> 1 100 1.8 -2.2
> 2 101 1.8 -1.7
>
> I tried the following:but didn't make it work, any inputs would be greatly
> appreciated.
>
> for (i in 1:nrow(myDF)) {
> + myrow <-myDF[i,]
> + don't know how to move forward?
> + }
>
> --
> View this message in context: http://r.789695.n4.nabble.com/rows-process-in-DF-tp2289378p2289378.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.
>
More information about the R-help
mailing list