[R] Summing certain values within columns that satisfy a certain condition
Jeff Newmiller
jdnewmil at dcn.davis.CA.us
Thu Feb 26 22:29:27 CET 2015
I guess the answer to your question is "yes".
dta <- read.table( text=
"A B C D
0 1 0 7
0 2 0 7
0 3 0 7
0 4 0 7
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 5
0 5 1 5
0 4 1 5
0 8 4 7
0 0 3 0
0 0 3 4
0 0 3 4
0 0 0 5
0 2 0 6
0 0 4 0
0 0 4 0
0 0 4 0
", header=TRUE )
dtacmax <- sapply( dta, max )
followed by
dta$Sum <- apply(dta,1, function(x) (sum(0!=x & x == dtacmax,na.rm=TRUE)))
or
dtam <- as.matrix( dta[,1:4] )
dta$Sum2 <- rowSums( !is.na(dtam) & 0!=dtam & dtam == matrix( dtacmax, ncol=ncol( dtam ), nrow=nrow( dtam ), byrow=TRUE ) )
---------------------------------------------------------------------------
Jeff Newmiller The ..... ..... Go Live...
DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live Go...
Live: OO#.. Dead: OO#.. Playing
Research Engineer (Solar/Batteries O.O#. #.O#. with
/Software/Embedded Controllers) .OO#. .OO#. rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.
On February 26, 2015 12:23:48 PM PST, Kate Ignatius <kate.ignatius at gmail.com> wrote:
>Hi,
>
>Supposed I had a data frame like so:
>
>A B C D
>0 1 0 7
>0 2 0 7
>0 3 0 7
>0 4 0 7
>0 1 0 0
>0 0 0 0
>0 0 0 0
>0 0 0 0
>0 0 1 5
>0 5 1 5
>0 4 1 5
>0 8 4 7
>0 0 3 0
>0 0 3 4
>0 0 3 4
>0 0 0 5
>0 2 0 6
>0 0 4 0
>0 0 4 0
>0 0 4 0
>
>For each row, I want to count how many max column values appear to
>adventurely get the following outcome, while ignoring zeros and N/As:
>
>A B C D Sum
>0 1 0 7 1
>0 2 0 7 1
>0 3 0 7 1
>0 4 0 7 1
>0 1 0 0 0
>0 0 0 0 0
>0 0 0 0 0
>0 0 0 0 0
>0 0 1 5 0
>0 5 1 5 0
>0 4 1 5 0
>0 8 4 7 3
>0 0 3 0 0
>0 0 3 4 0
>0 0 3 4 0
>0 0 0 5 0
>0 2 0 6 0
>0 0 4 0 1
>0 0 4 0 1
>0 0 4 0 1
>
>I've used the following code but it doesn't seem to work (my sum
>column column is all 1s):
>
>(apply(df,1, function(x) (sum(x %in% c(pmax(x))))))
>
>Is this code too simple?
>
>Thanks!
>
>K.
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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