如何在数据框中添加多个字符列?

时间:2015-11-18 12:51:15

标签: r string dataframe data.table

我喜欢这个

   Peak  number
ALDH9A1       0
ALDH9A1       2
   RPL4       2
   RPL4       8
TP53BP1       0
TP53BP1       1
   TOM1       7
   TOM1      17

我想创建四个新的列,其中包含字符和数字的组合,如下所示

Met  Char  Type Made     Peak  number
111    A    AAK ADDR  ALDH9A1       0
111    B    AAK ADDR  ALDH9A1       2
111    A    AAK ADDR     RPL4       2
111    B    AAK ADDR     RPL4       8
111    A    AAK ADDR  TP53BP1       0
111    B    AAK ADDR  TP53BP1       1
111    A    AAK ADDR     TOM1       7
111    B    AAK ADDR     TOM1      17

1 个答案:

答案 0 :(得分:2)

尝试:

library(dplyr)
df %>%
  mutate(Type = "AAK", Met = 111, Made = "ADDR") %>%
  group_by(Peak) %>%
  mutate(Char = LETTERS[row_number()])

给出了:

#Source: local data frame [8 x 6]
#Groups: Peak [4]
#
#     Peak number  Type   Met  Made  Char
#   (fctr)  (int) (chr) (dbl) (chr) (chr)
#1 ALDH9A1      0   AAK   111  ADDR     A
#2 ALDH9A1      2   AAK   111  ADDR     B
#3    RPL4      2   AAK   111  ADDR     A
#4    RPL4      8   AAK   111  ADDR     B
#5 TP53BP1      0   AAK   111  ADDR     A
#6 TP53BP1      1   AAK   111  ADDR     B
#7    TOM1      7   AAK   111  ADDR     A
#8    TOM1     17   AAK   111  ADDR     B