[R] Mapping one vector to another

Geoff Leyland geoff_leyland at fastmail.fm
Tue Jun 12 04:27:39 CEST 2012


Hi, I'm new here,

I'd like to map a set of values in a data frame to another set of values in another frame (think a c++ map<>, a python dict or a hash lookup)

Specifically, I have a data frame of information about trading periods in the NZ electricity market. For each period I have information about each bus (or node) in the network.  I'd like add a "column" to the data frame containing the island that the bus is on.

I'm afraid my success at searching for an answer is restricted by not knowing what this operation might be called in R, but I found a something on stackoverflow [1] and tried the following:

 map <- read.table("../node_islands.csv", header=TRUE, sep=",")
 map <- setNames(map$island, map$node)
 periods$Island = map[periods$Bus]

Where after the first line, but before the second and third:

> map[1:3,]
    node island
1 ABY0111     SI
2 ABY1101     SI
3 ADD0111     SI

and:

> periods[1:3, c("Date", "Period", "Bus", "Price")] 
       Date Period     Bus Price
1 2004-01-01      1 ABY0111 31.20
2 2004-01-01      1 ADD0111 32.43
3 2004-01-01      1 ADD0661 32.38

This seems to work (it fooled me for quite a while :-) ), but the following check:

 for (b in periods$Bus)
 {
   if (periods[periods$Bus == b, "Island"] != map[b])
   {
     print(b)
     print(periods[periods$Bus == b, "Island"][1:1])
     print(map[b])
   }
 }

prints a number of lines where periods$Island does not match the corresponding value in map:

[1] "ALB0331"
[1] SI
Levels: NI SI
ALB0331 
    NI 
Levels: NI SI
[1] "APS0111"
[1] NI
...

Clearly, I've missed the point here.  Would anyone be so kind as help me find it or suggest which FM I might need to R?

Cheers,
Geoff

[1] http://stackoverflow.com/questions/7547597/dictionary-style-replace-multiple-items-in-r



More information about the R-help mailing list