Reputation: 43
I'm trying to create a new column with the range of numbers from 0-40 in the total impressions column.
I'm trying to utilize the ifelse function, if that pertains here. This is what I have so far:
group1 <-rocketfuel[rocketfuel$total_impr==<-ifelse(rocketfuel$total_imp<=40, rocketfuel$tot_impr ]
The goal is to break up the customers into 6 group based on number of impressions, so group 1 will be 0-40 impressions, group 2 will be 41-80 impressions and so on.
Update: Utilizing one of the solutions given below, which is almost exactly what I'm looking for
rocketfuel$group1 <- ifelse(rocketfuel$tot_impr<=40,1,NA)
Instead of the group1 column spitting out the #1, I want it to spit out #21, is that possible?
Figured it out!
Upvotes: 0
Views: 934
Reputation: 56
Are you trying to subset the values of users who had fewer than 40 impressions or are you trying to create a group of users? Also, make sure your column names are consistent in the call (e.g. "total_imp" vs "total_impr").
rocketfuel <- data.frame(user_id=c(1069124,1119715,1144181,1435133,1015700),
test=rep(1,5),
converted=rep(0,5),
tot_impr=c(130,93,21,355,276),
mode_impr_day=c(1,2,2,2,5),
mode_impr_hour=c(20,22,18,10,14))
If you are trying to create a group, just add it as its own variable(column). Using ifelse() is similar to excel, you can do something like this
rocketfuel$group_lt_40 <- ifelse(rocketfuel$total_impr<=40,1,NA)
if you're trying to create a column of impressions under 40, you can still use ifelse() and keep the original value of impressions try:
rocketfuel$group_lt_40_impr <-ifelse(rocketfuel$total_impr<=40,rocketfuel$total_impr,NA)
Upvotes: 1
Reputation: 78927
library(dplyr)
df %>%
mutate(`0-40` = as.logical(ifelse(tot_impr>=0 & tot_impr<=40, TRUE, FALSE)))
Output:
user_id.s test converted tot_impr mode_impr_day mode_impr_hour `0-40`
<int> <int> <int> <int> <int> <int> <lgl>
1 1069124 1 0 130 1 20 FALSE
2 1119715 1 0 93 2 22 FALSE
3 1144181 1 0 21 2 18 TRUE
4 1435133 1 0 355 2 10 FALSE
5 1015700 1 0 276 5 14 FALSE
data:
df <- tibble::tribble(
~user_id.s, ~test, ~converted, ~tot_impr, ~mode_impr_day, ~mode_impr_hour,
1069124L, 1L, 0L, 130L, 1L, 20L,
1119715L, 1L, 0L, 93L, 2L, 22L,
1144181L, 1L, 0L, 21L, 2L, 18L,
1435133L, 1L, 0L, 355L, 2L, 10L,
1015700L, 1L, 0L, 276L, 5L, 14L
)
Upvotes: 1