Home > Blockchain >  How to count repeats in a list and store them as a multiple?
How to count repeats in a list and store them as a multiple?

Time:05-06

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). enter image description here

enter image description here 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.

CodePudding user response:

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"))

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related