SHRram
SHRram

Reputation: 4227

counting particular number repetition in r

Here is small example:

A <- c(1,1,1,1, 0, 0, 0, 2,2,2)
B <- c(1,1,1,1, 0, 0, 0, 0,2,2)
C <- c(1,1,3,3, 0,0, 2,2,2, NA)
myd <- data.frame (A, B, C)

I need to apply a function say "prod" (prod (myd$myvar, na.rm = TRUE), before applying I need to count number of 0's.

(1) If number zeros are equal to or less than 3, I need to replace with NA
    myd$A[myd$A ==0] <- NA

(2) If  number of zeros are greater than 3, no replacement action need to be done.
   myd$B[myd$B ==0] <- 0 

How can I count zeros and apply the coditions to get the results.

Edit: In the above dataset, A and C meets condition 1 and B condition 2.

Upvotes: 2

Views: 558

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162341

Are you looking for something like this?

f <- function(X) {
    if(sum(X==0, na.rm=TRUE) <= 3) X[X==0] <- NA
    X
}

data.frame(lapply(myd, f))
#     A B  C
# 1   1 1  1
# 2   1 1  1
# 3   1 1  3
# 4   1 1  3
# 5  NA 0 NA
# 6  NA 0 NA
# 7  NA 0  2
# 8   2 0  2
# 9   2 2  2
# 10  2 2 NA

Upvotes: 3

Related Questions