0
votes

I have a data.frame with x values which I would like to count depending of two factors: the first one is the value of x, the second one depends on a factor. Here's a sample

set.seed(111)
A<-data.frame(x=rnorm(n = 100,mean = 5,sd=1))
A$LETTER<-sample(LETTERS[1:2],100,replace=T)
A$int<-cut(A$x,breaks=c(0,3,6,9))

I need a frequency value for the x within a certain interval but with an extra condition.

Count for Letter = A (0,3) x values and for letter = B (6,9) values

Count for both Letters (3,6) as one

Count the reverse of the first condition

Output could be a new data.frame

To make it clear

table(A$int,A$LETTER)
       
         A  B
  (0,3]  2  1
  (3,6] 32 49
  (6,9]  9  7

In this case, first sum should be 2+7, second sum should be 1+9 and third sum should be 32+49

1

1 Answers

1
votes

You can try this:

library(dplyr)
as.integer(table(filter(A, LETTER == 'A')$int) + rev(table(filter(A, LETTER == 'B')$int)))

Output will be:

[1]  9 81 10

Note, you don't really need dplyr and you can do filtering differently as follows:

as.integer(table(A[A$LETTER == 'A', ]$int) + rev(table(A[A$LETTER == 'B', ]$int)))