Home > Software engineering >  Changing statue based on other factors using R
Changing statue based on other factors using R

Time:10-16

So I have a key factor lk that generate random number between 1 and 9. Based on that factor some change must occur in my data as follows;

My data looks like this:

statue cost salary
t 43 21
n 5 17
n 27 21
n 26 35
t 39 38
n 12 22
t 42 13
t 38 32
n 39 15
t 25 38

If lk > sum (df$statue=="t") say lk == 7 and sum (df$statue=="t") == 5 so two individuals with statue=="n" and the smallest cost must change their status from n to t in this example individual 2 and 6.

And if lk <= sum (df$statue=="t") say lk == 3 and sum (df$statue=="t") == 5 so two individuals with statue=="t" and the biggest salary must change their status from t to n in this example individual 5 and 10.

I hope I made it clear;

Any ideas please;

Best regards

CodePudding user response:

Not sure if this is what you wanted...

check_lk <- function(lk, data){
  sum_t <- nrow(data[data$statue == "t",])
  if(lk > sum_t){
    # create reordered data, by statue and cost (ascending order)
    tmp <- data[order(data$statue, data$cost),]
    # first two records represent statue n and two lowest cost
    # add another conditional check if needed
    tmp[1:2, "statue"] <- "t"
    tmp <- tmp[ order(as.numeric(row.names(tmp))), ]
  } else{ 
    # create reordered data, by statue and salary (ascending order)
    tmp <- data[order(data$statue, data$salary),]
    tmp[c(nrow(tmp), nrow(tmp)-1), "statue"] <- "n"
    tmp <- tmp[ order(as.numeric(row.names(tmp))), ]
  }
  return(tmp)
}

Loading data given:

df <- structure(list(statue = c("t", "n", "n", "n", "t", "n", "t", 
"t", "n", "t"), cost = c(43L, 5L, 27L, 26L, 39L, 12L, 42L, 38L, 
39L, 25L), salary = c(21L, 17L, 21L, 35L, 38L, 22L, 13L, 32L, 
15L, 38L)), class = "data.frame", row.names = c(NA, -10L))

Test for lk = 7

check_lk(7, df)

   statue cost salary
1       t   43     21
2       t    5     17
3       n   27     21
4       n   26     35
5       t   39     38
6       t   12     22
7       t   42     13
8       t   38     32
9       n   39     15
10      t   25     38

Test for lk=3

check_lk(3, df)
   statue cost salary
1       t   43     21
2       n    5     17
3       n   27     21
4       n   26     35
5       n   39     38
6       n   12     22
7       t   42     13
8       t   38     32
9       n   39     15
10      n   25     38
  • Related