[R] Vector indexing question
Marc Schwartz
marc_schwartz at comcast.net
Fri Mar 30 02:51:20 CEST 2007
On Thu, 2007-03-29 at 19:55 -0400, Paul Lynch wrote:
> Suppose you have 4 related vectors:
>
> a.id<-c(1:25, 1:25, 1:25)
> a.vals <- c(101:175) # same length as a.id (the values for those IDs)
> a.id.levels <- c(1:25)
> a.id.ratings <- rep(letters[1:5], times=5) # same length as a.id.levels
>
> What I would like to do is specify a rating from a.ratings (e.g. "e"),
> get the vector of corresponding IDs from a.id.levels (via
> a.id.levels[a.id.ratings=='e']) and then somehow use those IDs in a.id
> to get the corresponding values from a.vals.
>
> I think I can probably write a loop to construct of a vector of
> ratings of the same length as a.id so that the ratings match the ID,
> and then go from there. Is there a better way? Perhaps using factors
> or levels or something?
>
> Thanks,
> --Paul
Is this what you want?
DF <- data.frame(a.id, a.vals, a.id.levels, a.id.ratings)
> DF[DF$a.id.ratings == "e", "a.vals"]
[1] 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175
or
> subset(DF, a.id.ratings == "e", select = a.vals)
a.vals
5 105
10 110
15 115
20 120
25 125
30 130
35 135
40 140
45 145
50 150
55 155
60 160
65 165
70 170
75 175
See ?subset
HTH,
Marc Schwartz
More information about the R-help
mailing list