[R] Mapping one vector to another

Rui Barradas ruipbarradas at sapo.pt
Tue Jun 12 14:35:37 CEST 2012


Hello,

Try, after the first instruction but before the second and third,

merge(periods, map, by.x="Bus", by.y="node", all.x=TRUE)


Also, it's better to use dput() to give data examples. To paste the 
output of this or similar in a post is the recomended way:

dput(head(periods, 20))  # or 30, or enough to be representative


Hope this helps,

Rui Barradas

Em 12-06-2012 03:27, Geoff Leyland escreveu:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list