[R] Matching two datasets and updating values
Petr PIKAL
petr.pikal at precheza.cz
Tue Oct 4 14:37:34 CEST 2011
Hi
>
> Dear R forum
>
> I have two datafarmes with category and cat_val forming one dataframe
and
> cust and cust_category forming another dataframe.
>
> category = c("C", "D", "B", "A")
> cat_val = c(0.10, 0.25, 0.40, 0.54)
> cust = c("cust_1", "cust_2", "cust_3", "cust_4", "cust_5", "cust_6",
> "cust_7", "cust_8", "cust_9", "cust_10")
> cust_category = c("C", "A", "A", "A", "A", "C", "D", "B", "B", "D")
>
> Thus, I have
>
> > category
> [1] "C" "D" "B" "A"
>
> > cat_val
> [1] 0.10 0.25 0.40 0.54
>
> > cust
> [1] "cust_1" "cust_2" "cust_3" "cust_4" "cust_5"
> [6] "cust_6" "cust_7" "cust_8" "cust_9" "cust_10"
>
> > cust_category
> [1] "C" "A" "A" "A" "A" "C" "D" "B" "B" "D"
>
> My problem is to match 'cust_category' with 'category' and accordingly
> selct the value assigned to this category value. In other words, 1st
> element of cust_category is "C", so it should select the value 0.10, the
> second element is "A", so it should assign value 0.54 against this. So
> effectively I should get
What about merge?
a<-data.frame(category, cat_val)
b<-data.frame(cust, cust_category)
merge(a,b, by.x="category", by.y="cust_category")
category cat_val cust
1 A 0.54 cust_3
2 A 0.54 cust_4
3 A 0.54 cust_5
4 A 0.54 cust_2
5 B 0.40 cust_8
6 B 0.40 cust_9
7 C 0.10 cust_1
8 C 0.10 cust_6
9 D 0.25 cust_7
10 D 0.25 cust_10
Regards
Petr
>
> cust cust_category cat_val
> cust_1 C 0.10
> cust_2 A 0.54
> cust_3 A 0.54
> ............................................
> cust_10 D 0.25
>
>
> Kindly guide
>
> Regards
>
> Vincy
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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