r - Line by line value assigning in dataframe -


i know title might not explicit, sorry, can't find better one.

i'm trying following

foo<-123456                         # doesn't matter, know it's value ifelse(my_df$number / foo < 0.75,   #for each row of my_df, see if number / sum under 0.75        ifelse(                      # if is...          my_df$number / foo < 0.5,  # check if under 0.5          my_df$class<-"in50",       # if is, assign value "in50" in "class" field of row                        my_df$class<-"in75"),      # else, assign "in75" class field of row                     my_df$class<-"in100")        # if it's not under 0.75, assign "in100" class field of row 

my problem assigning operator :

if use <- whole class column ends being in100 (because last value should in100).

if use =, :

error: unexpected '=' in: "my_df$number / sum < 0.5, my_df$class="

and obviously, == not need.

any advice ?

edit : commented code make expected result clearer

we can use findinterval

 i1 <- with(my_df, findinterval(number/foo, c(0.5, 0.75)))   my_df$class <- c('in50', 'in75', 'in100')[i1+1l]  head(my_df$class)  #[1] "in50"  "in50"  "in100" "in100" "in100" "in100"   head(my_df$number/foo)  #[1] 0.472 0.360 1.128 0.832 1.064 1.480 

data

 foo <- 125    set.seed(24)  my_df <- data.frame(number= sample(1:200,                                     100, replace=true)) 

Comments