1

I have to write all first letters of a string with 9 words in a new string. Is there a better way to do it than:

    eg <- "This is a test I developed"
    temp.eg <- strsplit(eg,' ')[[1]]
    temp.eg <- substr(temp.eg, 0, 1)
    new.eg <- paste(temp.eg, collapse = "")

Also, is there another way of splitting the string, so I dont have to use:

strsplit() [[1]]
zx8754
  • 52,746
  • 12
  • 114
  • 209
Toby Kal
  • 27
  • 7

2 Answers2

4

You can use gsub to extract the first letter and words boundary (\\b):

gsub("\\b(\\w)(\\b|(\\w+))( |$)", "\\1", eg)
[1] "TiatId"

Explanation: you're asking for a "word" character (\\w) that comes after a word boundary and that is followed by either a word boundary or more word character then either a space or the end of the string ($).


Another option given by @lukeA:

gsub("(?<!\\b).|\\s", "", eg, perl=TRUE)
[1] "TiatId"

It uses look-behind (?<!: before must not be...) to "suppress" (replace by empty string) anything or a space which follows anything that is not a word boundary.

Cath
  • 23,906
  • 5
  • 52
  • 86
3

To avoid [[ subset we can use unlist, the rest of your code looks fine:

paste(substr(unlist(strsplit(eg, " ")), 1, 1), collapse = "")
# [1] "TiatId"

If we have more than one string:

egLong <- c("This is a test I developed", "another test me")

sapply(strsplit(egLong, " "), function(i){
  paste(substr(i, 1, 1), collapse = "")
  })
# [1] "TiatId" "atm" 
zx8754
  • 52,746
  • 12
  • 114
  • 209