Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly add quotes and commas to a list of items for c() in R?

Tags:

r

This is a matter of convenience more than anything. I'm often adding quotes and commas by hand to make a c() list for some other function. Is there a quick and clever way to add them that doesn't involve tricky find/replaces or multiple operations? If I have multiple items separated by a space or tab, or one item per line I'd like to do the following:

A B C D

or

A

B

C

D

to:

temp <- c("A", "B", "C", "D")

I can add them by hand, do a find/replace for the whitespace to ", " and then add in the first/last, but that is annoying. Is there a quicker way?

like image 696
user974887 Avatar asked Mar 04 '19 19:03

user974887


People also ask

How do you add quotation marks in R?

To add single quotes to strings in an R data frame column, we can use paste0 function. This will cover the strings with single quotes from both the sides but we can add them at the initial or only at the last position.

How do you use quotation marks in a list?

Quotation marks and other punctuation marks In the United States, the rule of thumb is that commas and periods always go inside the quotation marks, and colons and semicolons (dashes as well) go outside: “There was a storm last night,” Paul said. Peter, however, didn't believe him.

How do you list multiple quotes in a row?

'” When multiple quotation marks are used for quotations within quotations, keep the quotation marks together (put periods and commas inside both; put semi-colons, colons, etc., outside both).


1 Answers

The scan function is the basis for all the read.* functions, but it also serves to execute the task you desire executed. A couple of years ago a text parameter was added so you no longer need to wrap textConnection around "naked strings". Can be used with any delimiter and the default whitespace delimiter will handle what yopu ask to be processed:

 TEMP <- scan(text="A B C D", what="")

#-------------------
Read 4 items
> TEMP
[1] "A" "B" "C" "D"
> dput(TEMP)
c("A", "B", "C", "D")

If you need to maintain leading zeros on what might be numeric, then you will need to either import them as text or prepend the leading zeros when printing them with formatC or sprintf

like image 180
IRTFM Avatar answered Sep 21 '22 03:09

IRTFM