Rey Rey - 1 month ago 6
R Question

r - prefixing specific column titles in data frame

Hello absolute noob here so apologies if I don't know exactly what you are telling me first without a bit of a google to help me understand!

I have a data frame with 6 cols, four of which contain the word qPCR, i.e

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))


I have multiple dataframes like this looking at different genes so I want to prefix the columns with qPCR in them with the gene name, i.e

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)
)


I had thought about using rename, but could only change one column title at a time. was then thinking grepl and rename might do it, but not sure how to implement these together?

any help would be much appreciated.

Answer

You can use paste0 to add leading genes at required columns. What the below piece of code does is that it identifies (grepl) which columns have the word 'qPCR' and adds the string 'gene_' using paste0.

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