Reputation: 1145
I've a data frame, and one of the variables (w1) is a factor with seven levels. Here are the first few lines:
X number delta1 tossc w1
1 0.743477269 0 1 <NA>
2 0.742817675 0 1 x1
3 0.867432987 0 1 x5
4 0.535971961 1 1 Group3
5 0.743477269 0 1 x2
6 0.742817675 0 1 x1
7 0.867432987 0 1 <NA>
8 0.535971961 1 1 Group3 or Group4
How can find number of times each character has appeared in w1? (for example, x1 appeard 2 times, x5 appeared 1 time, etc.). Any help will be appreciated.
Upvotes: 0
Views: 198
Reputation: 1336
An alternative would be:
length(which(dat$w1=="x1"))
which can be easily saved as a new variable.
Upvotes: 0
Reputation: 121578
Here a solution using merge
and table
merge(dat,as.data.frame(table(dat$w1)),by.x='w1',by.y='Var1')
w1 X number delta1 tossc Freq
1 <NA> 1 0.7434773 0 1 2
2 <NA> 7 0.8674330 0 1 2
3 Group3 4 0.5359720 1 1 1
4 Group3 or Group4 8 0.5359720 1 1 1
5 x1 2 0.7428177 0 1 2
6 x1 6 0.7428177 0 1 2
7 x2 5 0.7434773 0 1 1
8 x5 3 0.8674330 0 1 1
Upvotes: 2