Shweta
Shweta

Reputation: 23

Trying to calculate aging and write it into a newly added column in excel dynamically in R

Function group_tenure is working but not able to write “0-1 Days” etc in new column along with the filtered value. Here TodayNew is the column in excel which has aging.

group_tenure  <- function(TodayNew){
  if (TodayNew >= 0 & TodayNew <= 1){
     return ('0-1 Days')
  }else if(TodayNew > 1 & TodayNew <= 4){
    return('2-4 Days')
  }else if (TodayNew > 4 & TodayNew <= 7){
     return('5-7 Days')
  }else if (TodayNew > 7 & TodayNew <=15){
     return('8-15 Days')
  }else if (TodayNew > 15 & TodayNew <=30){
     return('16-30 Days')
  }else if (TodayNew > 30){
    return('More than 30 Days')
  }
}

Showing values of group_tenure as below but not able to write in new column.

group_tenure(1)
[1] "0-1 Days"
> group_tenure(2)
[1] "2-4 Days"
> group_tenure(5)
[1] "5-7 Days"
> group_tenure(8)
[1] "8-15 Days"
> group_tenure(16)
[1] "16-30 Days"
> group_tenure(31)
[1] "More than 30 Days"

Upvotes: 0

Views: 49

Answers (1)

r2evans
r2evans

Reputation: 160447

Your function is not vectorized, so if I'm interpreting you correctly, it will not be something you can call on a vector (i.e., data frame column).

x <- c(1, 2, 5, 8, 16, 31)
group_tenure(x)
# Warning in if (TodayNew >= 0 & TodayNew <= 1) { :
#   the condition has length > 1 and only the first element will be used
# [1] "0-1 Days"

If you need that, then either use

Vectorize(group_tenure)(x)
# [1] "0-1 Days"          "2-4 Days"          "5-7 Days"          "8-15 Days"        
# [5] "16-30 Days"        "More than 30 Days"

or vectorize your function. One way to do that efficiently here is to use cut:

group_tenure2 <- function(TodayNew) {
  as.character(
    cut(TodayNew, c(0, 1, 4, 7, 15, 30, Inf),
        labels = c("0-1 Days", "2-4 Days", "5-7 Days", "8-15 Days", "16-30 Days", "More than 30 Days"),
        include.lowest = TRUE)
  )
}
group_tenure2(x)
# [1] "0-1 Days"          "2-4 Days"          "5-7 Days"          "8-15 Days"        
# [5] "16-30 Days"        "More than 30 Days"

Upvotes: 1

Related Questions