I have a column containing different strings which are repeated along the column. I wanted to create another column which will basically sum up the number of occurrences of strings and fill this column with the number. This is equivalent to using countif function in excel.
Asked
Active
Viewed 2,085 times
0
-
1Have a look at `table` – emilliman5 May 30 '17 at 10:48
-
Do you want just the number of occurrences for each unique string, or the number of occurrences up to that cell ? e.g. col=`A,A,B,A,B` --> you want `A=3,B=2` or a column saying : `1,2,1,3,2` ? – digEmAll May 30 '17 at 10:52
-
3Welcome to SO! What have you tried so far? Please read [ask] and [mcve] ... then edit your question: https://stackoverflow.com/posts/44259842/edit – jogo May 30 '17 at 10:56
-
Do you want just the number of occurrences for each unique string, or the number of occurrences up to that cell ? e.g. col=A,A,B,A,B --> you want A=3,B=2 or a column saying : 1,2,1,3,2 ? I want the later thanks. – Sthitapragnya Kalita May 31 '17 at 11:48
1 Answers
0
for example:
s <- c("aaa","aab","aba","abb","bbb")
look_for_what <- "aa"
length(s[grep(look_for_what,s)])
# 2
look_for_what <- "a"
length(s[grep(look_for_what,s)])
# 4

JCR
- 71
- 7