0

Lets say that I imported a csv into R and it looks like this.

1 4 3 5
9 6 2 6 

and I have another csv with something like

1 apple
2 banana
3 toast
4 beer
5 chips
6 cheese
9 wine

Is there a way to use the second one to label the values in the first? I hope that makes sense.

florianm
  • 71
  • 1
  • 3
  • 1
    What are the R classes of the objects involved. Are you treating the data in the first CSV like a data.frame? A character matrix? What is the class of the desired output? Rather than pasting random text, it's helpful to create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with proper R objects so we can see the structure. Check out the answers at that link for tips on how to do that. – MrFlick Sep 23 '14 at 20:02
  • 1
    You could do something like `x2$col1[match(names(x1), rownames(x2))]` – Rich Scriven Sep 23 '14 at 20:19

1 Answers1

3

Here's a possible approach :

# recreate your input data
vals <- read.table(
text=
"1 4 3 5
9 6 2 6")

map <- read.table(
text=
"1 apple
2 banana
3 toast
4 beer
5 chips
6 cheese
9 wine",stringsAsFactors=F)
names(map) <- c('K','V')


# - turn vals into a vector (using unlist function)
# - get the row indexes of the unlisted keys corresponding 
#   to map keys (using match function)
# - using the indexes select the key names in map (using vector subsetting [])
# - turn the character vector into 2d matrix with original dimension of vals
# - coerce to data.frame
mapped <- as.data.frame(matrix(map$V[match(unlist(vals),map$K)],nrow=nrow(vals)))

# > mapped
# V1     V2     V3     V4
# 1 apple   beer  toast  chips
# 2  wine cheese banana cheese
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • 1
    Edit: merge returns unordered rows so it is hardly usable for this case. This solution use match function as suggested by @RichardScriven – digEmAll Sep 23 '14 at 20:37