R - Merge unique values from two lists using stringr::str_split

Viewed 99

I have a function, that when given a list of strings, should return a vector of all unique strings of N size.

get_unique <- function (input_list, size = 3) {
   output = c()

   for (input in input_list) {
    current = stringr::str_replace(input, "[-_\\s]", "")
    current = trimws(gsub(paste0("(.{",size,"})"), "\\1 ", current))
    parts = stringr::str_split(current, "\\s", simplify = TRUE)[1,]
    output = union(output, parts)
   }

   return(output)
}

The expectation I have would be:

get_unique(c("ABC", "ABCDEF", "GHIDEF"))

[1] "ABC" "DEF" "GHI"

But what I get is:

get_unique(c("ABC", "ABCDEF", "GHIDEF"))

[[1]]
[1] "ABC"

[[2]]
[1] "DEF"

[[3]]
[1] "GHI"

I'm fairly new to R, so I'm having a tough time understanding where I've gone wrong.

2 Answers

We can use unlist at the end

get_unique <- function (input_list, size = 3) {
  output = c()

  for (input in input_list) {
     current = stringr::str_replace(input, "[-_\\s]", "")
     current = trimws(gsub(paste0("(.{",size,"})"), "\\1 ", current))
    parts = stringr::str_split(current, "\\s", simplify = TRUE)[1,]
    output = union(output, parts)
  }

  return(unlist(output))
 }

get_unique(c("ABC", "ABCDEF", "GHIDEF"))
#[1] "ABC" "DEF" "GHI"

We could also do this in a single line with a regex lookaround to split at every 3 character

unique(unlist(strsplit(v1, "(?<=...)", perl = TRUE)))
#[1] "ABC" "DEF" "GHI"

data

v1 <- c("ABC", "ABCDEF", "GHIDEF")

full on baseR solution, using substr:

get_unique <- function(v) unique(unlist(sapply(v, function(x) sapply(1:(nchar(x)/3), function(y) substr(x, 3*(y-1)+1, 3*y) ))))

get_unique(v1)
[1] "ABC" "DEF" "GHI"
  • substr(x, 3*(y-1)+1, 3*y) grab 3 characters substrings from x.
Related