【问题标题】:r - prefixing specific column titles in data framer - 在数据框中为特定列标题添加前缀
【发布时间】:2017-03-03 12:22:15
【问题描述】:

你好,绝对的菜鸟,如果我不知道你首先告诉我的确切内容,没有一点谷歌来帮助我理解,我深表歉意!

我有一个包含 6 个列的数据框,其中四个包含单词 qPCR,即

sample..id...mean_qPCR..sd_qPCR..sem_qPCR..total_qPCR

Data <- data.frame( sample = sample(1:10), id = sample(1:10), mean_qPCR =sample(1:10), sd_qPCR = sample(1:10), sem_qPCR = sample(1:10), total_qPCR = sample(1:10))

我有多个像这样查看不同基因的数据框,所以我想在其中的 qPCR 列前加上基因名称,即

sample..id...gene_mean_qPCR..gene_sd_qPCR..gene_sem_qPCR..gene_total_qPCR

Data <- data.frame( sample = sample(1:10), id = sample(1:10), gene_mean_qPCR = sample(1:10), gene_sd_qPCR = sample(1:10), gene_sem_qPCR = sample(1:10), gene_total_qPCR = sample(1:10) )

我曾考虑过使用重命名,但一次只能更改一个列标题。当时在想 grepl 和 rename 可能会这样做,但不确定如何一起实现这些?

任何帮助将不胜感激。

【问题讨论】:

  • 你从哪里得到基因名称?
  • @Sotos 我想我将手动添加的基因名称,目前唯一可以从中获取的位置是数据框的名称,但那里也有其他名称
  • 好的。为了帮助我们帮助您,最好的办法是提供reproducible example 和预期结果。
  • 类似 @Sotos 的东西?顺便说一句,感谢您的帮助,正如我所说,对 r 非常陌生,第一次发布堆栈溢出

标签: r dataframe rename


【解决方案1】:

您可以使用paste0 在所需列中添加前导基因。下面这段代码的作用是识别 (grepl) 哪些列包含单词 'qPCR' 并使用 paste0 添加字符串 'gene_'。

names(Data)[grepl('qPCR', names(Data))] <- paste0('gene_', names(Data)[grepl('qPCR', names(Data))])

head(Data)
#  sample id gene_mean_qPCR gene_sd_qPCR gene_sem_qPCR gene_total_qPCR
#1     10  3              4            7             8               1
#2      5  1              2            5             3               7
#3      6 10              9           10            10               9
#4      2  5              6            3             9               8
#5      4  4              1            4             5               6
#6      9  6              3            1             4               4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2017-08-26
    相关资源
    最近更新 更多