r - Character frequency in a string -
i want create function 2 arguments show me frequency of character in given word: x <- word, y <- letter. so, created following function:
frequency <- function(x,y) { word <- strsplit(x,"") counter <- 0 (i in 1:length(word)){ if (word[i] == y) counter=counter+1 } print(counter) }
the basic idea of function split characters of given word, iterate on them , increase value of counter if condition met. function returns value of 0. what's cause of this?
as noted frank, better avoid loops. can so:
word <-"word" y <-"d" sum(unlist(strsplit(word,""))==y) [1] 1
Comments
Post a Comment