R语言paste函数解析

我怕爱的太早我们不能终老 提交于 2020-03-20 10:42:56

R语言paste函数解析

paste函数

paste函数的作用就是将R对象转换为字符后连接向量。

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

参数

  • ... 一个或多个R对象,要转换为字符向量。

  • sep 分隔字符串。不是NA_character_。

  • collapse 分隔结果的可选字符串。不是NA_character_。

从上参数列表可知,...参数和sep参数是必须参数,collapse参数是可选参数。

其中,

...参数,可以有一个或多个对象。

sep参数,的默认值为空格" "

collapse参数因为是可选参数,所以它的默认值就是空NULL。

所以对于paste函数的学习,重点就是学会sep参数和collapse参数。

理解sep 和collapse参数

代码示例用法

> LETTERS
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U"
[22] "V" "W" "X" "Y" "Z"
> letters
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u"
[22] "v" "w" "x" "y" "z"

# sep默认为空格
> paste(LETTERS,letters)
 [1] "A a" "B b" "C c" "D d" "E e" "F f" "G g" "H h" "I i" "J j" "K k" "L l" "M m" "N n"
[15] "O o" "P p" "Q q" "R r" "S s" "T t" "U u" "V v" "W w" "X x" "Y y" "Z z"
> paste(LETTERS,letters, sep = "_")
 [1] "A_a" "B_b" "C_c" "D_d" "E_e" "F_f" "G_g" "H_h" "I_i" "J_j" "K_k" "L_l" "M_m" "N_n"
[15] "O_o" "P_p" "Q_q" "R_r" "S_s" "T_t" "U_u" "V_v" "W_w" "X_x" "Y_y" "Z_z"

# collapse设置后,将结果的各个元素连接成一个字符串。
> paste(LETTERS,letters, sep = "_", collapse = '.')
[1] "A_a.B_b.C_c.D_d.E_e.F_f.G_g.H_h.I_i.J_j.K_k.L_l.M_m.N_n.O_o.P_p.Q_q.R_r.S_s.T_t.U_u.V_v.W_w.X_x.Y_y.Z_z"

# collapse设置后,将一个对象的各个元素连接成一个字符串。
> paste(LETTERS,collapse = '.')
[1] "A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z"

与expand.grid函数联合使用实现循环拼接

代码示例

> LETTERS[1:4]
[1] "A" "B" "C" "D"
> expand.grid(LETTERS[1:4], 1:4)
   Var1 Var2
1     A    1
2     B    1
3     C    1
4     D    1
5     A    2
6     B    2
7     C    2
8     D    2
9     A    3
10    B    3
11    C    3
12    D    3
13    A    4
14    B    4
15    C    4
16    D    4
# 首先给出所有元素的搭配组合
> expand.grid(LETTERS[1:4], 1:4)
   Var1 Var2
1     A    1
2     B    1
3     C    1
4     D    1
5     A    2
6     B    2
7     C    2
8     D    2
9     A    3
10    B    3
11    C    3
12    D    3
13    A    4
14    B    4
15    C    4
16    D    4
# 每一行的元素组合进行拼接,返回一个字符串向量
> apply(expand.grid(LETTERS[1:4], 1:4), 1, paste, collapse = "_")
 [1] "A_1" "B_1" "C_1" "D_1" "A_2" "B_2" "C_2" "D_2" "A_3" "B_3" "C_3" "D_3" "A_4" "B_4"
[15] "C_4" "D_4"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!