Assign vector to longer vector by group

时间:2016-04-04 17:08:17

标签: r match assign

I've been struggling to assign values to some groups in some data, but I am somewhat stuck. I've tried matching unique's and rep and other. I hope someone here can help me.

I have a data set that looks like this

df <- data.frame(
GRP.id  = c(1, 2, 2, 2, 3, 3),
group  = c("A", "B", "B", "B", "C", "C"))
> df
  GRP.id group
1      1     A
2      2     B
3      2     B
4      2     B
5      3     C
6      3     C

and a vector with some values that need to be assign to each group

value <- c(.3, .8, .3)

such that I get this result

  GRP.id group value
1      1     A   0.3
2      2     B   0.8
3      2     B   0.8
4      2     B   0.8
5      3     C   0.3
6      3     C   0.3

1 个答案:

答案 0 :(得分:2)

df$value <- value[match(df$GRP.id,unique(df$GRP.id))];
df;
##   GRP.id group value
## 1      1     A   0.3
## 2      2     B   0.8
## 3      2     B   0.8
## 4      2     B   0.8
## 5      3     C   0.3
## 6      3     C   0.3

If you know for a fact that the df$GRP.id column will always consist of 1:n for some max n, then you can replace the match(df$GRP.id,unique(df$GRP.id)) piece with just df$GRP.id. But for robustness (i.e. just in case that assumption will not always be true) I'd go with the match()/unique() design.