[英]Convert DataFrame to String in R
I have a dataframe in the format in an excel (there are many more names):我有一个 dataframe 格式为 excel (还有更多名称):
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:我必须将这些名称放在 SQL 查询中,我需要它们以以下格式作为字符串:
'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 (\).这不起作用,因为这会在 output (\) 中产生反斜杠。 Even using shQuote gives reverse slashes.
即使使用 shQuote 也会给出反斜杠。
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)如果我直接声明它,我会得到在 SQL 查询中工作的所需输入,(只是一个例子,我不能使用它,因为名称不断变化)
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?有没有办法 go 关于它?
You may use dput
.您可以使用
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所以如果你有一个向量说
students
,那么
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)由代表 package (v2.0.1) 于 2022 年 8 月 29 日创建
You could do this:你可以这样做:
paste0("'",students,"'",collapse = ",")
Output: 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.