서영빈
서영빈

Reputation: 106

How to sum the column, only if the vector is '>0'?

I wonder how to sum all the column, only if the vector is bigger than '0'.

I've got 'DF' like this.

A   B 
-14 4
-13 4
-12 3
-4  4
-1  4
0   4
1   4
2   3
3   4
4   4
.
.
.

And I want to A*B, especially if the vector is '>0'. So finally I want to get sum of '1*4, 2*3 , 3*4 , 4*4'.

What I tried is this

exp<- function(x){
 a<-c()
 for (y in c(1:nrow(DF)){
  if (DF[y,A]>0) {
 return (a<-c(a, DF[y,A] * DF[y,B]))
}
 else if (DF[y,A]<=0) {
 return (a<-c(a,0))
}
 result <- sum(a)
 result
}

But I think this code is too heavy. Especially the 'for in' code makes this function too slow. How can I make this code simpler?

Upvotes: 2

Views: 81

Answers (3)

Cole
Cole

Reputation: 11255

Here's a data.table solution:

library(data.table)

setDT(DF)
DF[A > 0, sum(A*B)]

Or a similar solution using dplyr.

library(dplyr)

DF%>%
  filter(A > 0)%>%
  summarize(C = sum(A * B))

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

Another base R possibility could be:

sum(with((df > 0) * df, A * B))

[1] 38

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521467

Try subsetting the data frame to only include rows in the sum both of whose A and B values are positive:

sum(df[df$A > 0 & df$B > 0, "A"]*df[df$A > 0 & df$B > 0, "B"])

[1] 38

Data:

df <- data.frame(A=c(-14,-13,-12,-4,-1,0,1,2,3,4),
                 B=c(4,4,3,4,4,4,4,3,4,4))

Upvotes: 1

Related Questions