line_to_vector: Turn a Line of Items into a Vector or c() Code

line_to_vectorR Documentation

Turn a Line of Items into a Vector or c() Code

Description

This function takes a line of items separated by spaces, tabs, or newlines and returns either a c() vector command (with items quoted or not) or the vector created by that command. By default, the line is read from the clipboard and a character vector is returned. The function uses only the highest-level separator present in x unless specified otherwise. This functionality is particularly useful for copying values from spreadsheet programs like Excel (or from R console output) and converting them into R vectors seamlessly.

Usage

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

l2v(
  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 line breaks. If NULL, the function will attempt to read from the clipboard.

strings

Logical or NULL. Determines whether vector items should be treated as strings (i.e., quoted). Defaults to TRUE unless all items are numeric.

separators

Character string indicating which separator should be used to split x. Defaults to the highest-level separator found in x (i.e., newlines if present). Can also be "all" to split by all supported separators (i.e. spaces: " ", commas: ",", tabs: "\t", newlines: "\n").

to_clip

Logical. Indicates whether the generated code for the vector should be copied to the clipboard. Defaults to TRUE in interactive sessions. Requires the clipr package to be installed.

keep_blank_as_na

Logical. If TRUE, empty values are kept as NA. If FALSE (default), empty values are omitted from the resulting vector.

return_type

Character string specifying the type of return value. Choose "code" to return the c() command as a string or "vector" to return the actual R vector. Defaults to "code". Abbreviated values like "c" or "v" are accepted.

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.

Value

A character string representing the c() command or the actual R vector, depending on the return_type parameter.

Examples


line_to_vector("a b c", strings = TRUE)
# c("a", "b", "c")


line_to_vector("1 2 3", return_type = "vector")
# [1] 1 2 3

# Can abbreviate return argument
# [1] "Friday"   "Saturday" "Sunday"


LukasWallrich/timesaveR documentation built on Nov. 29, 2024, 4:47 a.m.