Home > OS >  Change the row names in R
Change the row names in R

Time:09-07

i have two dataframes with similar rownames:

> rownames(abundance)[1:10]
 [1] "X001.V2.fastq_mapped_to_agora.txt.uniq" 
 [2] "X001.V8.fastq_mapped_to_agora.txt.uniq" 
 [3] "X003.V17.fastq_mapped_to_agora.txt.uniq"
 [4] "X003.V2.fastq_mapped_to_agora.txt.uniq" 
 [5] "X003.V8.fastq_mapped_to_agora.txt.uniq" 
 [6] "X004.V2.fastq_mapped_to_agora.txt.uniq" 
 [7] "X004.V8.fastq_mapped_to_agora.txt.uniq" 
 [8] "X005.V2.fastq_mapped_to_agora.txt.uniq" 
 [9] "X005.V8.fastq_mapped_to_agora.txt.uniq" 
[10] "X006.V2.fastq_mapped_to_agora.txt.uniq" 
> rownames(fluxes)[1:10]
 [1] "001.V8"  "003.V17" "003.V2"  "003.V8"  "004.V2"  "004.V8"  "005.V2" 
 [8] "005.V8"  "006.V2"  "006.V8" 

But the row names of the dataframe abundance is larger. How can i make the names of each rows like the rownames of fluxes. It can be like from "X" to second ".".

CodePudding user response:

We could use sub:

rownames(abundance) <- sub("X(.*)\\.fastq_mapped_to_agora\\.txt\\.uniq", "\\1", rownames(abundance))

Output:

[1] "001.V2"  "001.V8"  "003.V17" "003.V2"  "003.V8"  "004.V2"  "004.V8"  "005.V2"  "005.V8"  "006.V2" 

CodePudding user response:

We may use trimws

rownames(abundance) <- trimws(rownames(abundance), whitespace = "\\..*")

Or could be

rownames(abundance) <- sub("^([^.] \\.[^.] )\\..*", "\\1", rownames(abundance))

-testing

> trimws("X001.V2.fastq_mapped_to_agora.txt.uniq",  whitespace = "\\..*")
[1] "X001"
> sub("^([^.] \\.[^.] )\\..*", "\\1", "X001.V2.fastq_mapped_to_agora.txt.uniq")
[1] "X001.V2"
  • Related