美文网首页R
R语言 字符串拼接

R语言 字符串拼接

作者: 唐伯虎点蚊香7 | 来源:发表于2019-05-02 22:21 被阅读78次

    1. paste {base}

    语法:

    paste (..., sep = " ", collapse = NULL)
    paste0(..., collapse = NULL)

    两个参数:sep字符串内的拼接符;collapse字符串间的拼接符。pastepaste0的区别:paste0参数sep默认为空字符,paste的参数sep默认为空格。

    示例:
    paste("1st", "2nd", "3rd", collapse = ", ")
    [1] "1st 2nd 3rd"
    
    paste("1st", "2nd", "3rd", sep = ", ")
    [1] "1st, 2nd, 3rd"
    
    paste(c("a", "b", "c"),c(1:3) , sep = ": ", collapse = "; ")
    [1] "a: 1; b: 2; c: 3"
    

    2. str_c {stringr}

    语法:

    str_c(..., sep = "", collapse = NULL)

    参数:与paste一致,但对NA的处理方法不一致。

    示例:
    library("stringr")
    str_c("Letter: ", letters)
     [1] "Letter: a" "Letter: b" "Letter: c" "Letter: d" "Letter: e" "Letter: f" "Letter: g" "Letter: h"
     [9] "Letter: i" "Letter: j" "Letter: k" "Letter: l" "Letter: m" "Letter: n" "Letter: o" "Letter: p"
    [17] "Letter: q" "Letter: r" "Letter: s" "Letter: t" "Letter: u" "Letter: v" "Letter: w" "Letter: x"
    [25] "Letter: y" "Letter: z"
    
    #str_c在对含NA的字符拼接后,结果仍然为NA
    str_c(c("a", NA, "b"), "-d")
    [1] "a-d" NA    "b-d"
    #paste在对含NA的字符拼接后,NA被当作为“NA”字符串处理
    paste(c("a", NA, "b"), "-d")
    [1] "a -d"  "NA -d" "b -d"
    

    相关文章

      网友评论

        本文标题:R语言 字符串拼接

        本文链接:https://www.haomeiwen.com/subject/zmsonqtx.html