Brandon Bertelsen
Brandon Bertelsen

Reputation: 44658

Simplifying input of strings with strsplit()

How can I reproduce this:

x <- strsplit('
Statement A
Statement B
Statement C
', '\n')[[1]][-1]

With a format that looks like this:

x <- someFunction(
Statement A
Statement B
Statement C
)

I'm getting really tired of copying and pasting ', '\n')[[1]][-1]. The overall goal here is to avoid having to type "double quotes" around each string.

Upvotes: 1

Views: 788

Answers (2)

Sacha Epskamp
Sacha Epskamp

Reputation: 47582

One thing you can do is use scan():

x <- scan(what="character",sep="\n")
Statement A
Statement B
Statement C

x
[1] "Statement A" "Statement B" "Statement C"

Though that simply replaces one thing to copy paste with another. If you don't want that, why not just make a wrapper function that does exactly what you say above?

spl <- function(x)
{
foo <- unlist(strsplit(x,'\n'))
foo[foo!=""]
}

spl('
Statement A
Statement B
Statement C
')
[1] "Statement A" "Statement B" "Statement C"

EDIT: If you really want to avoid the ' signs, then I think a short named wrapper function around the scan() statement is your best bet:

foo <- function(x)scan(what="character",sep="\n")

x <- foo()
Statement A
Statement B
Statement C

You could cook something up with a function using the ... sign, and match.call() to get it as characer, but when you use spaces that does not work anymore (as they are invalid object names, and you need the ` sign.

Upvotes: 4

Chase
Chase

Reputation: 69201

Does unlist do what you want?

someFunction <- function(txt) {
  unlist(strsplit(txt, "\n"))
}

#Dummy data
txt <- "Statement A
Statement B
Statement C"

> z <- someFunction(txt)
> all.equal(x,z)
[1] TRUE

Upvotes: 2

Related Questions