Reputation: 81
I am trying to code the following
I have 240 rows and 11 columns. I want to do the following: If the value in (row 1, column 1) was greater than 0 and if the value in (row 1, column 2) was greater than 0, then count the value in (row 1, column 4).
For an example: (row,column)
If (1,1) = (1) AND if (1,2)=(1) then count the value in (1,4)
If (2,1) = (1) AND if (2,2)=(0) then DO NOT COUNT the value in (2,4)
If (3,1) = (0) AND if (3,2)=(1) then DO NOT COUNT the value in (3,4)
etc...
I have already seen a quite similar post, however there was only 1 condition given instead of 2.
I tried the following solution, which did not work sum(DataFrame_a[DataFrame_a[ ,1] > 0, DataFrame_a[ ,2] > 0, 4])
Thank you in advance for your help.
Upvotes: 3
Views: 340
Reputation: 81
Thank you both for your help. It works now.
I did the following:
true_sum<-sum(Data[Data[,1]==1 & Data[,2]==1, 4])
that did the trick.
Thx again!
Upvotes: 0
Reputation: 947
I agree with Peter Hahn; an ifelse statement should do the trick.
Using dplyr is more elegant. For completeness, here is an example in base:
x <- data.frame("X1" = 1:5, "X2" = c(0,1,0,1,1), "X3" = 10:14)
y <- NULL
y <- ifelse(x$X1 > 0 & x$X2 > 0, x$X3,0)
> y
[1] 0 11 0 13 14
> sum(y)
[1] 38
Upvotes: 0
Reputation: 158
your only true condition is:
If (1,1) = (1) AND if (1,2)=(1) then count the value in (1,4)
I don't understand count the value
maybe this solution:
dplyr::mutate(new=ifelse(col1==1&col2==1,col4,0)
gives you a new column Hope that solves your problem
Upvotes: 1