如何将双引号和逗号添加到 R 数据框中的列?

How to add Double quotes and comma to a column in R dataframe?

我有一个只有一列的数据框。我希望列中的所有值都用双引号和逗号括起来,如下所示。

df <- data.frame("SN" = 1:4, "Name" = c("John", "Dora","Peter","Lilly"), stringsAsFactors = FALSE)

df$Name 

当我提取 Name 列时,我希望它 df$Name

"John",
"Dora",
"Peter",
"Lilly"

我尝试了 pastegsubshQuote,但没有给我想要的结果。感谢任何帮助。

data.frame(
  SN = 1:4,
  Name = c("John", "Dora", "Peter", "Lilly"),
  stringsAsFactors = FALSE
) -> xdf

sprintf():

sprintf('"%s",', xdf$Name)
## [1] "\"John\","  "\"Dora\","  "\"Peter\"," "\"Lilly\","

cat(sprintf('"%s",', xdf$Name), sep="\n")
## "John",
## "Dora",
## "Peter",
## "Lilly",

paste():

paste('"', xdf$Name, '",', sep = "")
## [1] "\"John\","  "\"Dora\","  "\"Peter\"," "\"Lilly\","

cat(paste('"', xdf$Name, '",', sep = ""), sep="\n")
## "John",
## "Dora",
## "Peter",
## "Lilly",

sub():

sub("$", '",', sub("^", '"', xdf$Name))
## [1] "\"John\","  "\"Dora\","  "\"Peter\"," "\"Lilly\","

cat(sub("$", '",', sub("^", '"', xdf$Name)), sep="\n")
## "John",
## "Dora",
## "Peter",
## "Lilly",

FWIW sprintf() 获胜:

microbenchmark::microbenchmark(
  sprintf = sprintf('"%s",', xdf$Name),
  paste = paste('"', xdf$Name, '",', sep = ""),
  sub = sub("$", '",', sub("^", '"', xdf$Name))
)
## Unit: microseconds
##     expr    min      lq     mean  median      uq     max neval
##  sprintf 11.705 13.4955 25.91594 19.6095 32.1780 170.989   100
##    paste 13.133 15.3150 34.31982 19.0455 31.9615 340.482   100
##      sub 31.271 34.8555 64.41124 39.8840 78.0180 533.065   100

更新

我猜你的目标是:

paste0(sprintf('"%s"', xdf$Name), collapse = ", ")
## [1] "\"John\", \"Dora\", \"Peter\", \"Lilly\""

cat(paste0(sprintf('"%s"', xdf$Name), collapse = ", "))
## "John", "Dora", "Peter", "Lilly"