Home > Mobile >  Create and apply a function that calculates the length of many strings in a vector
Create and apply a function that calculates the length of many strings in a vector

Time:05-04

Suppose I have a long vector with characters which is more or less like this:

vec <- c("32, 25", "5", "15, 24")

I want to apply a function which give me the number of strings for any element separated by a comma and returns me a vector with any individual length. Using lapply and my toy vector, this is my approach:

  lapply(vec, function(x) {
    a <- strsplit(x, ",")
    y <- length(a[[1:length(a)]])
    unlist(y[1:length(y)])
    })

[[1]]
[1] 2

[[2]]
[1] 1

[[3]]
[1] 2

This almost gives me what I want since first element has 2 strings, second element 1 string and third element 2 strings. The problem is I can't achieve that my function returns me a vector of the form c(2,1,2). I'm using this function to create a new variable on some data.frame which I'm working with. Any idea will be much appreciated.

CodePudding user response:

You could do:

stringr::str_count(vec, ",")   1
#> [1] 2 1 2

Or, in base R:

nchar(gsub("[^,]", "", vec))   1
#> [1] 2 1 2
  • Related