0

Lets say I have this file (main)

Name samp1 samp2 samp3 samp4
pg1 0.43 0.32 0.21 0.54
pg2 0.43 0.22 1.00 0.44
pg3 0.11 0.99 0.78 0.54
pg4 0.65 0.32 0.12 0.23

I also have this header file below (MAPPERS)

SampName ID
samp1 TYC
samp4 GDD
samp6 DER
samp2 JKK
samp3 WER
samp9 AXC

I wish to change all the headers of my "main" file using the "MAPPERS" file, such that if there is a match with the sampleName, then it should be replaced by the sample IDs. So I expect to have the following:

Name TYC JKK WER GDD
pg1 0.43 0.32 0.21 0.54
pg2 0.43 0.22 1.00 0.44
pg3 0.11 0.99 0.78 0.54
pg4 0.65 0.32 0.12 0.23

I have a large file, so can anyone help me how to get the above?

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Letin
  • 1,255
  • 5
  • 20
  • 36
  • Please post a sample of your data using `dput`, possibly in conjunction with `head` to make your question [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Ari B. Friedman Nov 22 '12 at 23:08

2 Answers2

1

?match is the tool you are chasing I reckon:

main <- read.table(textConnection("Name samp1 samp2 samp3 samp4
pg1 0.43 0.32 0.21 0.54
pg2 0.43 0.22 1.00 0.44
pg3 0.11 0.99 0.78 0.54
pg4 0.65 0.32 0.12 0.23"),header=TRUE,stringsAsFactors=FALSE)

mapper <- read.table(textConnection("SampName ID
samp1 TYC
samp4 GDD
samp6 DER
samp2 JKK
samp3 WER
samp9 AXC"),header=TRUE,stringsAsFactors=FALSE)


names(main)[2:5] <- mapper$ID[match(names(main)[2:5],mapper$SampName)]
main

  Name  TYC  JKK  WER  GDD
1  pg1 0.43 0.32 0.21 0.54
2  pg2 0.43 0.22 1.00 0.44
3  pg3 0.11 0.99 0.78 0.54
4  pg4 0.65 0.32 0.12 0.23
thelatemail
  • 91,185
  • 12
  • 128
  • 188
0

Here's an untested example. When you post data, I'll test it.

curnames <- data.frame(SampName=colnames(main))
colnames(main) <- merge(curnames,MAPPERS,all.x=TRUE)$ID

More code is required if you aren't certain that every SampName gets matched to an ID in MAPPERS.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235