Using dplyr count number of special characters rowwise and mutate into a new column

Viewed 98

An example data frame:

example_df = data.frame(Gene.names = c("A", "B"),
                        Score = c("3.69,2.97,2.57,3.09,2.94",
                                  "3.99,2.27,2.89,2.89,2.00,2.52,2.09,2.83") )

I want to count the number of 'numbers' (values) separated by commas in each row of 'Score' column and create a new column, say 'Count'. How can I do this? I tried to google but am not getting much help there.

2 Answers

We can use str_count on the , and add 1

library(stringr)
library(dplyr)
example_df %>% 
     mutate(Count = str_count(Score, ",") + 1)

-output

#  Gene.names                                   Score Count
#1          A                3.69,2.97,2.57,3.09,2.94     5
#2          B 3.99,2.27,2.89,2.89,2.00,2.52,2.09,2.83     8

Or using base R with gsub remove the characters that are not a ,, get the number of characters with nchar and add 1

nchar(gsub("[^,]+", "", example_df$Score)) + 1
#[1] 5 8

Another base R option is using strsplit + lengths, e.g.,

transform(
  example_df,
  Count = lengths(strsplit(Score,","))
)

which gives

  Gene.names                                   Score Count
1          A                3.69,2.97,2.57,3.09,2.94     5
2          B 3.99,2.27,2.89,2.89,2.00,2.52,2.09,2.83     8
Related