1
\$\begingroup\$

I would like to change row names values from a first data frame if these rows names are present in another data frame, and change it to a corresponding value (defined in the second data frame). I could do it with a for loop, but I wonder what would be some other more suitable ways to do it in R.

Here is a toy dataset (my real dataset has 10^5 rows):

df <- data.frame("sample_1" = rep(0,3), "sample_2" = rep(0,3), row.names = paste0('gene_', seq(1, 3)), stringsAsFactors = FALSE)
annotation <- data.frame("gene" =  paste0('gene_', seq(1, 2)), 'name' = paste0('name_', seq(1, 2)), stringsAsFactors = FALSE)
df$gene <- rownames(df)

Initial data frames:

df 
       sample_1 sample_2   gene
gene_1        0        0 gene_1
gene_2        0        0 gene_2
gene_3        0        0 gene_3

annotation
    gene   name
1 gene_1 name_1
2 gene_2 name_2

Solution found:

for (x in rownames(df)){
  if (x %in% annotation$gene){
    df[x,]$gene <- annotation$name[which(annotation$gene == x)]
  }
}
rownames(df) <- df$gene
df$gene <- NULL

Resulting data frame:

df
       sample_1 sample_2
name_1        0        0
name_2        0        0
gene_3        0        0
\$\endgroup\$
1
\$\begingroup\$
df$gene <- rownames(df)
df <- merge(df, annotation, by = 'gene', all.x = T, sort = F, )
rownames(df) <- ifelse(!is.na(df$name), df$name, df$gene)
df$gene <- df$name <- NULL
df
#        sample_1 sample_2
# name_1        0        0
# name_2        0        0
# gene_3        0        0
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.