【问题标题】:R Create Custom ListR 创建自定义列表
【发布时间】:2020-02-08 03:31:38
【问题描述】:
paste0("a",1:5)
"a1" "a2" "a3" "a4" "a5"

我想要这个输出: “a1”、“a2”、“a3”、“a4”、“a5”

我试过 paste0("a",1:5, sep=",") 也试过 paste0("a",1:5, collapse=",") 但这些都没有。

【问题讨论】:

  • 你需要toString(paste0("a",1:5))还是paste0("a",1:5, collapse = ",")
  • @RonakShah 没有这样做,谢谢。

标签: r string paste


【解决方案1】:

你可以使用

paste0('"a', 1:5, '"', collapse = ',')
#[1] "\"a1\",\"a2\",\"a3\",\"a4\",\"a5\""

R 使用反斜杠打印引号,查看实际字符串使用cat

cat(paste0('"a', 1:5, '"', collapse = ','))
#"a1","a2","a3","a4","a5"

【讨论】:

  • 如果我希望将其存储在 VEC 中怎么办? VEC=cat(paste0('"a', 1:5, '"', collapse = ',')) 只打印不存储
  • 你应该使用vec <- paste0('"a', 1:5, '"', collapse = ',')。它使用cat 存储您看到的内容,但是当您打印它时,这就是 R 显示带引号的字符串的方式。
  • This Is OutPut: "\"a1\",\"a2\",\"a3\",\"a4\",\"a5\"" 当使用此代码存储时。这可以吗,还是会寻找\
  • 是的,这就是字符串有引号时的样子 ("")。
【解决方案2】:

我们也可以使用stringr中的str_c

library(stringr)
str_c('"a', 1:5, '"', collapse=",")
#[1] "\"a1\",\"a2\",\"a3\",\"a4\",\"a5\""

或者base RdQuotepaste

dQuote(paste0('a', 1:5), q = FALSE)

【讨论】:

    猜你喜欢
    • 2014-12-10
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多