Home > database >  How to get the number of elements separated by an underscore
How to get the number of elements separated by an underscore

Time:03-02

strings<-c("A_A_A","B", "C_C_C_C", "D_D_D_D_D")

I have this vector of strings. I want to have the number of elements in each string so that to have:

[1] 3  1  4  5

CodePudding user response:

stringr::str_count(c("A_A_A","B", "C_C_C_C", "D_D_D_D_D"), '_')   1

CodePudding user response:

For a base R option, we could use string replacement:

strings <- c("A_A_A","B", "C_C_C_C", "D_D_D_D_D")
nchar(strings) - nchar(gsub("_", "", strings, fixed=TRUE))   1

[1] 3 1 4 5

CodePudding user response:

You can use lengths with strsplit.

strings <- c("A_A_A", "B", "C_C_C_C", "D_D_D_D_D")

lengths(strsplit(strings, split = "_"))
# [1] 3 1 4 5

CodePudding user response:

Yet another possible solution:

library(tidyverse)

strings<-c("A_A_A","B", "C_C_C_C", "D_D_D_D_D")

strings %>% 
  str_remove_all("_") %>% 
  str_count

#> [1] 3 1 4 5

CodePudding user response:

Another option with nchar gsub

> nchar(gsub("[^_]", "", strings))   1
[1] 3 1 4 5

or

> nchar(gsub("_", "", strings))
[1] 3 1 4 5

CodePudding user response:

If your structure is always like your sample data, that means 1 character seperated by one length seperator you can simply do

ceiling(nchar(strings)/2)

# [1] 3 1 4 5
  •  Tags:  
  • r
  • Related