Reputation: 3711
Seems, I am missing some link here. I have data frame
df<-data.frame(w=sample(1:3,10, replace=T), x=sample(1:3,10, replace=T), y=sample(1:3,10, replace=T), z=sample(1:3,10, replace=T))
> df
w x y z
1 3 1 1 3
2 2 1 1 3
3 1 3 2 2
4 3 1 3 1
5 2 2 1 1
6 1 2 2 3
7 1 2 2 2
8 2 2 2 3
9 1 3 3 3
10 2 2 1 1
I want to get the number of rows of each column which matches to 1st column.
sum(df$w==df$x)
[1] 3
sum(df$w==df$y)
[1] 2
sum(df$w==df$z)
[1] 1
I know using apply, I can do rowwise or colwise operations.
apply(df,2,length)
w x y z
10 10 10 10
How do I combine these two functions?
Upvotes: 3
Views: 86
Reputation: 92292
Try colSums
colSums(df[-1] == df[, 1])
# x y z
# 3 2 1
Or if you into *apply
loops could try
vapply(df[-1], function(x) sum(x == df[, 1]), double(1))
Upvotes: 4