Skip to content
Prev 169820 / 398506 Next

Generating new variable based on values of an existing variable

on 02/09/2009 01:30 PM Josip Dasovic wrote:
I am going to presume that unlike your example data above, the real data
may not be sequenced in unique sequential runs. Thus, a more general
approach would be to set mydf$region as a factor, with the factor levels
set to match 1:1 the sequence in 'elements':

 mydf$region <- factor(mydf$region,
                       levels = c("North", "East", "South", "West"))

 element <- c("earth", "water", "air", "fire")

# Set mydf$element to the value in 'element' which corresponds to the
# underlying factor integer code for mydf$region

  mydf$element <- element[as.numeric(mydf$region)]
region element
1   North   earth
2   North   earth
3   North   earth
4   North   earth
5   North   earth
6    East   water
7    East   water
8    East   water
9    East   water
10   East   water
11  South     air
12  South     air
13  South     air
14  South     air
15  South     air
16   West    fire
17   West    fire
18   West    fire
19   West    fire
20   West    fire


HTH,

Marc Schwartz