R: compute the length of text data in a column

Viewed 127

I have the following csv data myData:

   name   attribute
1  Name1  attr11,attr12,attr13
2  Name2  attr21
3  Name3  attr31,attr32

I want to plot the distribution of the number of attributes, to do that I need to loop through each row, and tokenize the data in the column attribute, and count the length. Essentially, that should give a vector or another data with the same length as the original myData

I have tried:

num_attr <- length(as.list(strsplit(myData$attribute, ",")))  #this just returns 3

and:

num_attr <- as.list(strsplit(myData$attribute, ","))

this returns a list something like:

["attr11" "attr12" "attr13", "attr21", "attr31" "attr32"]

I am also thinking of using apply(), like apply(myData, 1, func) but I am not sure what func to put in.

In summary, how do I plot the distribution/density of the number of attributes?

2 Answers

The output of strsplit() is a list, so if you want the number of elements in each split you should use an *apply function. Try this:

num_attr <- sapply(strsplit(x = myData$attribute, split = ','), length)

this applies length() to each list element (each split) and returns a vector of length N (where N is the number of rows in myData).

If you want num_attr as a list do:

num_attr <- lapply(strsplit(x = myData$attribute, split = ','), length)

We can also count the number of , in the 'attribute' column

library(stringr)
str_count(myData$attribute, ",") + 1
#[1] 3 1 2

data

myData <- structure(list(name = c("Name1", "Name2", "Name3"), 
 attribute = c("attr11,attr12,attr13", 
"attr21", "attr31,attr32")), class = "data.frame", 
 row.names = c("1", 
"2", "3"))
Related