Column Column R

I want to add a column containing the number of letters az in another column from the same row.

dataset$count <-length((gregexpr('[a-z]', as.character(dataset$text))[[1]]))

does not work.

The result that I would like to get:

text  |  count
a     |  1
ao    |  2
ao2   |  2
as2e  |  3
as2eA |  3
+5
source share
2 answers

Difficult:

nchar(gsub("[^a-z]","",x))
+14
source

This should do the trick:

numchars<-function(txt){
  #basically your code, but to be applied to 1 item
  tmpres<-gregexpr('[a-z]', as.character(txt))[[1]]
  ifelse(tmpres[1]==-1, 0, length(tmpres))
}
#now apply it to all items:
dataset$count <-sapply(dataset$text, numchars)

Another option is a two-step approach:

charmatches<-gregexpr('[a-z]', as.character(dataset$text))[[1]]
dataset$count<-sapply(charmatches, length)
+1
source

All Articles