Acronym in R: not working

Can somebody help me to find the error in my response?

acronym <- function(input) {
    ac1 <- strsplit(input, " ")
    ac2 <- unlist(strsplit(ac1, "-"))
    for (word in ac2) {
      result <- ""
      result <- append(result, word[1])
      }
    final <- toString(result)
    final <- toupper(final)
    return(final)
}
── Error: Abbreviate a phrase ──────────────────────────────────────────────────
Error in `strsplit(ac1, "-")`: non-character argument
Backtrace:
    β–†
 1. β”œβ”€testthat::expect_equal(acronym(input), "PNG")
 2. β”‚ └─testthat::quasi_label(enquo(object), label, arg = "object")
 3. β”‚   └─rlang::eval_bare(expr, quo_get_env(quo))
 4. └─global acronym(input)
 5.   β”œβ”€base::unlist(strsplit(ac1, "-"))
 6.   └─base::strsplit(ac1, "-")

Error: Test failed
Execution halted

Error in 'strsplit(ac1, "-")': non-character argument
This seem to be the current problem.

You split the main string (input) into a list of strings (ac1), then the line below you call the split function again on the just created list (ac1), and the function won’t accept a list as argument.

What should happen is you apply the strsplit function again on each string inside the list (ac1)

@glaxxie I’m almost there, can u help me?

acronym <- function(input) {
  ac1 <- strsplit(input, " ")
  for(word in ac1){
    result <- ""
    result <- append(result, strsplit(word, "-"))
    }
  final <- ""
  for (word in result) {
    final <- append(final, substr(word,1,1))
  }
  final <- toString(final)
  final <- toupper(final)
  return(final)
}
── Failure: Abbreviate a phrase ────────────────────────────────────────────────
acronym(input) not equal to "PNG".
1/1 mismatches
x[1]: ", , P, N, G"
y[1]: "PNG"

Error: Test failed
Execution halted

Yes, you are very close.
Need to tweak this line a bit:

final <- toString(final)

As you can see from the error output, the string vector are not properly concatenate.

x[1]: ", , P, N, G"
y[1]: "PNG"

You should consider using a different function: paste

thank you very much, @glaxxie
worked with gsub…

acronym <- function(input) {
  ac1 <- strsplit(input, " ")
  for(word in ac1){
    result <- ""
    result <- append(result, strsplit(word, "-"))
    }
  final <- ""
  for (word in result) {
    final <- append(final, substr(word,1,1))
  }
  final <- toString(final)
  final <- toupper(final)
  final <- gsub(",", "", gsub(" ", "" , gsub("_", "N", final)))
  return(final)
}
1 Like