简体   繁体   中英

R count character column

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

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

does not work.

The result I would like to acheive:

text  |  count
a     |  1
ao    |  2
ao2   |  2
as2e  |  3
as2eA |  3

棘手的一个:

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

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 more of a two-step approach:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM