Question

I want to count occurrences that match two criteria and assign that value to a cell (is cell the right word here?). So far, I've tried using nrow() and subset() to do the job, like so:

for (n in nrow(data)) {data[n,17] <- nrow(subset(data,(REP == data$REP[n]) & (Was.Sent. == "Sent")))/nrow(subset(data,REP == data$REP[n]))}

So far though, each cell is populating as "NA." What am I doing wrong, and is there a better/easier way to do this?

Was it helpful?

Solution

It looks like for every row, you could like to calculate the average number of sent items for the REP in the row. That actually can be better accomplished with the ave() function.

Here's a sample data set

data <- data.frame(
    Was.Sent=c("Sent","No")[c(1,1,2,1,2,1,2,1)],
    REP=c(1,2,3,1,2,3,1,2)
)

And here's the code that will add a new column with the desired percent

data$psent<-with(data, ave(Was.Sent=="Sent", REP, FUN=mean))

And if I view the results, I see

cbind(data,psent)[order(data$REP, data$Was.Sent),]
#  Was.Sent REP     psent
#7       No   1 0.6666667
#1     Sent   1 0.6666667
#4     Sent   1 0.6666667
#5       No   2 0.6666667
#2     Sent   2 0.6666667
#8     Sent   2 0.6666667
#3       No   3 0.5000000
#6     Sent   3 0.5000000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top