'Count repeats in a list and store them as a multiple
I have a list, which looks like this (the ID is the name of each element in the list and the scores are the values).

The problem is some of the elements contain duplicate values. For example: for ID = 8, the scores are: 1, 1, 2, 4.
I want to be able to count if there are any repeats and store the number of repeats. In this case: 1x2, 2, 4.
I have tried:
str_count(patient.variants[[8]], "1")
But this just returns: 1, 1, 0, 0.
Data for Example
list("1" = c("1", "2", "2"), "2" = c("1", "1", "2", "3"), "3" = c("1", "1", "2", "2"))
Solution 1:[1]
You can try
lapply(lst, \(x) {
tab <- table(x)
unname(ifelse(tab > 1, paste(names(tab), tab, sep = "x"), names(tab)))
})
# $`1`
# [1] "1" "2x2"
#
# $`2`
# [1] "1x2" "2" "3"
#
# $`3`
# [1] "1x2" "2x2"
Data
lst <- list("1" = c("1", "2", "2"),
"2" = c("1", "1", "2", "3"),
"3" = c("1", "1", "2", "2"))
Solution 2:[2]
An option with tapply
lapply(lst1, \(x) unname(tapply(x, x, FUN = function(x)
if(length(x) > 1) paste(x[1], length(x), sep = "X") else x)))
$`1`
[1] "1" "2X2"
$`2`
[1] "1X2" "2" "3"
$`3`
[1] "1X2" "2X2"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Darren Tsai |
| Solution 2 | akrun |
