Michal
Michal

Reputation: 1895

Applying ifelse with a grouping variable

I have data that contains an index and a season and would like to discretize this data. I created some fake data for demonstration:

data_frame <- data.frame(index=c(10,233.2,12,44,56,232,1.4,43,76,89,20.3,23), season=c('Fall','Winter','Fall','Summer','Winter','Spring','Spring','Summer','Winter','Spring','Summer','Fall'))
data_frame
   index season
1   10.0   Fall
2  233.2 Winter
3   12.0   Fall
4   44.0 Summer
5   56.0 Winter
6  232.0 Spring
7    1.4 Spring
8   43.0 Summer
9   76.0 Winter
10  89.0 Spring
11  20.3 Summer
12  23.0   Fall

Since in my original data, the distribution for each season is different, I would like to discretize the index grouping by the season variable. I am discretizing the data by assigning a 1 to anything above the 75th percentile for the group and 0 to anything below.

I would like the following output:

   index season  disc
1   10.0   Fall  0
2  233.2 Winter  1
3   12.0   Fall  0
4   44.0 Summer  1
5   56.0 Winter  0
6  232.0 Spring  1
7    1.4 Spring  0
8   43.0 Summer  0
9   76.0 Winter  0
10  89.0 Spring  0
11  20.3 Summer  0
12  23.0   Fall  1

I know how to find the result, but not in the format that I need. I am using the tapply function to discretize my variable:

tapply(data_frame$index, data_frame$season, function(x) ifelse(x>quantile(x,0.75),1,0))
$Fall
[1] 0 0 1

$Spring
[1] 1 0 0

$Summer
[1] 1 0 0

$Winter
[1] 1 0 0

How would I produce the output that I need?

Upvotes: 1

Views: 541

Answers (1)

jeremycg
jeremycg

Reputation: 24945

You can use dplyr:

library(dplyr)
data_frame %>% group_by(season) %>%
               mutate(disc = +(percent_rank(index) > 0.75))

   index season disc
1   10.0   Fall    0
2  233.2 Winter    1
3   12.0   Fall    0
4   44.0 Summer    1
5   56.0 Winter    0
6  232.0 Spring    1
7    1.4 Spring    0
8   43.0 Summer    0
9   76.0 Winter    0
10  89.0 Spring    0
11  20.3 Summer    0
12  23.0   Fall    1

edit using + to convert the TRUE FALSE to numberic as per Frank

Upvotes: 2

Related Questions