x <- tibble(
name = c("A", "B", "C"),
type = c("34;30;100;1;1;9;9;100;200;100;1;1","34;30;34","30;45;1;45;30;30")
)
How can I count the individual element (separated by ';') in the column 'type' so that I can know the total of each 'type' in the data frame?
For example, I'm looking to get a result like this:
# Given vector
type <- c("34;30;100;1;1;9;9;100;200;100;1;1", "34;30;34", "30;45;1;45;30;30")
# Split elements by semicolon and combine into a single vector
split_elements <- unlist(lapply(type, function(x) strsplit(x, ";")[[1]]))
# Count the frequency of each element
element_count <- table(split_elements)
# Convert the table to a data frame
element_count_df <- as.data.frame(element_count)
# Rename the columns
colnames(element_count_df) <- c("Element", "Count")
# Display the data frame
element_count_df
#> Element Count
#> 1 1 5
#> 2 100 3
#> 3 200 1
#> 4 30 5
#> 5 34 3
#> 6 45 2
#> 7 9 2