【问题标题】:Convert dataframe column to concatenated string without double quotes将数据框列转换为不带双引号的连接字符串
【发布时间】:2017-01-29 15:19:58
【问题描述】:

我有一个这样的data.frame:

df = data.frame(str_col = c("when xyz = 'some_string' then 'this_string'",
                            "when xyz = 'some_string2' then 'this_string'"))

我想将 str_col 转换为不带双引号的逗号分隔向量,例如:

c(when xyz = 'some_string' then 'this_string', when xyz = 'some_string2' then 'this_string')

我正在尝试这个: str_vec <- paste(shQuote(df$str_col), collapse=",")

但我明白了:

[1] "\"when xyz = 'some_string' then 'this_string'\",\"when xyz = 'some_string2' then 'this_string'\""

我不想要反斜杠或双引号。我正在尝试构建一个 SQL 查询。

【问题讨论】:

    标签: r string


    【解决方案1】:

    我认为你应该使用noquote 而不是shQuote

    str_vec <- paste(noquote(df$str_col), collapse=",")
    

    给出:

    > str_vec
    [1] "when xyz = 'some_string' then 'this_string',when xyz = 'some_string2' then 'this_string'"
    

    如果您还想删除上述结果周围的双引号,请将其再次包装在 noquote 中:

    str_vec <- noquote(paste(noquote(df$str_col), collapse=","))
    

    给出:

    > str_vec
    [1] when xyz = 'some_string' then 'this_string',when xyz = 'some_string2' then 'this_string'
    

    【讨论】:

    • 我在我想要的预期输出中犯了一个小错误。 .时间之间不应该有逗号,但我通过调整你的答案中的折叠参数来修复它。谢谢!
    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多