Home > Net >  use mutate to create column of lengths of string from previous column r
use mutate to create column of lengths of string from previous column r

Time:08-05

When I run the following program, I do not get the desired result.

library(dplyr)

dfr <- data.frame(sym = c("aa","bbb","c","dd"))

dfr %>% mutate( len = length(sym) )

The output is (mutate is clearly treating "sym" as the entire column instead of single entry)

  sym len
1  aa   4
2 bbb   4
3   c   4
4  dd   4

I want the output to be (note I must use mutate)

  sym len
1  aa   2
2 bbb   3
3   c   1
4  dd   2

CodePudding user response:

You should use stringr::str_count() to count the number of characters.

library(stringr)
libaray(dplyr)

dfr %>% mutate(len = str_count(sym))

  sym len
1  aa   2
2 bbb   3
3   c   1
4  dd   2

CodePudding user response:

Using nchar(sym) instead of length(sym) should get what you want.

  • Related