This takes a line of items separated by spaces, tabs or newlines and returns a c() vector command - with the items quoted or not - or a vector created by that command. By default, the line is read from the clipboard and a character vector returned, and only the highest-level separator present in x is used to split. Note that this makes it possible to copy values in most spreadsheet programs such as Excel and use this function to pull them from the clipboard and turn them into code that creates a vector.

line_to_vector(
  x = NULL,
  strings = NULL,
  separators = c("top-level", "all"),
  to_clip = interactive(),
  return = c("code", "vector"),
  keep_blank_as_na = FALSE
)

Arguments

x

Character string of desired vector items, separated by spaces, tabs or linebreaks. If NULL, it will be read from the clipboard.

strings

Should vector items be considered as strings, i.e. quoted. Defaults to treating them as string, unless all are numbers.

separators

Which separator should x be split by. This defaults to the "top-level" found in x, i.e., newlines, if there are any, and otherwise tabs or spaces. Can also be "all".

to_clip

Should code for vector be copied into clipboard? Defaults to TRUE in interactive use, but only works when clipr package is installed

return

Should code or a vector be returned? Defaults to code

keep_blank_as_na

By default, empty values are omitted. Set this to keep them as NA.

Details

If x is not split by spaces, stringr::str_trim() is used to trim whitespace from the start and end of each element of the vector.

Examples

line_to_vector("a b c", strings = TRUE)
#> [1] "c(\"a\", \"b\", \"c\")"

line_to_vector("1 2 3", return = "vector") # Returned as numeric vector
#> [1] 1 2 3

line_to_vector("Hello World!
                How are the bananas today?
                Thanks for being here.")
#> [1] "c(\"Hello World!\", \"How are the bananas today?\", \"Thanks for being here.\")"

weekend <- line_to_vector("Friday Saturday Sunday", return = "vector")