Home > Back-end >  Convert DataFrame to String in R
Convert DataFrame to String in R

Time:08-30

I have a dataframe in the format in an excel (there are many more names):

Student Name
John Martin
Steve Johnson
Alice Cramer
Lisa Green
Chandler Hans

. . .

I have to put these names in an SQL Query for which I need them to be in the following format as a string:

'John Martin','Steve Johnson','Alice Cramer','Lisa Green','Chandler Hans'

My Approach:

students<-read_xlsx("students.xlsx")
students<-paste0(students,collapse=",")

This doesn't work as this gives reverse slashes in the output (\). Even using shQuote gives reverse slashes.

If I declare it directly I get the required input which works in the SQL query, (just an example, I cannot use this as names are changing constantly)

students<-c('John Martin','Steve Johnson','Alice Cramer','Lisa Green','Chandler Hans')
students<-toString(sprintf("'%s'",students)

Is there a way to go about it ?

CodePudding user response:

You may use dput. see

dput(rownames(mtcars))
#> c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", 
#> "Hornet Sportabout", "Valiant", "Duster 360", "Merc 240D", "Merc 230", 
#> "Merc 280", "Merc 280C", "Merc 450SE", "Merc 450SL", "Merc 450SLC", 
#> "Cadillac Fleetwood", "Lincoln Continental", "Chrysler Imperial", 
#> "Fiat 128", "Honda Civic", "Toyota Corolla", "Toyota Corona", 
#> "Dodge Challenger", "AMC Javelin", "Camaro Z28", "Pontiac Firebird", 
#> "Fiat X1-9", "Porsche 914-2", "Lotus Europa", "Ford Pantera L", 
#> "Ferrari Dino", "Maserati Bora", "Volvo 142E")

So if you have a vector say students, then

dput(students)
#> c("John Martin", "Steve Johnson", "Alice Cramer", "Lisa Green", 
#> "Chandler Hans")

Created on 2022-08-29 by the reprex package (v2.0.1)

CodePudding user response:

You could do this:

paste0("'",students,"'",collapse = ",")

Output:

[1] "'John Martin','Steve Johnson','Alice Cramer','Lisa Green','Chandler Hans'"

Data used:

students<-c('John Martin','Steve Johnson','Alice Cramer',
            'Lisa Green','Chandler Hans')

> students
[1] "John Martin"   "Steve Johnson" "Alice Cramer"  "Lisa Green"    "Chandler Hans"
  •  Tags:  
  • r
  • Related