Count values separated by a comma in a character string

前端 未结 5 1247
小蘑菇
小蘑菇 2020-11-30 12:39

I have this example data

d<-\"30,3\"
class(d)

I have this character objects in one column in my work data frame and I need to be able to

5条回答
  •  旧巷少年郎
    2020-11-30 13:10

    A slight variation on the accepted answer, requires no packages. Using the example d <- c("1,2,3", "5,2")

    lengths(strsplit(d, ","))
    
    > [1] 3 2
    

    Or as a data.frame

    df <- data.frame(d = d)
    
    df$counts <- lengths(strsplit(df$d, ","))
    
    df
    
    #----
        d counts
    1,2,3      3
      5,2      2
    

提交回复
热议问题