user3323211
user3323211

Reputation: 55

Logic building help in R

I'm looking for a help to build a logic in R. I have a data set as shown in the imageSample_Data set

For any given Pack and ID:

  1. for the first occurrence, cost=Rates
  2. for the second occurrence, cost = Rates[Current]- Rates[Previous]
  3. For the third occurrence, cost = Rates[Current]- Rates[Previous]

I tried below piece of code, but the Cost column remain unaffected.

df_temp <- structure(list(Rates = c(100L, 200L, 300L, 400L, 500L, 600L), 
                          ID = structure(c(2L, 2L, 2L, 1L, 3L, 3L), .Label = c("wwww", 
                                                                               "xxxx", "yyyy"), class = "factor"), Pack = structure(c(1L, 
                                                                                                                                      1L, 2L, 1L, 2L, 2L), .Label = c("a", "b"), class = "factor"), 
                          Cost = c(100L, 100L, 300L, 400L, 500L, 100L)), class = "data.frame", row.names = c(NA, 
                                                                                                             -6L))

    calculate_TTF_or_S <- function(dput(df)){
      df <- arrange(df,ID,Rates)
      unique_sysids <- unique(df$ID)
      for (id in unique_sysids) {
        df_sub <- df[which(df$ID ==  id),]
        j=1
        for (i in seq_len(nrow(df_sub))){
          if (j==1){
            df$Cost[i] <- df_sub$Rates[j]
          } else {
            df$Cost[i] <- df_sub$Rates[j] - df_sub$Rates[j-1]
          }
          j <- j+1
        }
      }
      return (df$Cost)
    }


    df_temp$Cost <- calculate_TTF_or_S(df_temp)

Upvotes: 0

Views: 65

Answers (1)

Jon Spring
Jon Spring

Reputation: 66935

Here's a solution with dplyr.

library(dplyr)
df_temp %>%    # Start with your existing table...
  group_by(Pack, ID) %>%    # For each combination of Pack and ID...
  mutate(calc_cost = if_else(row_number() == 1,  # Add new column that is either...
                             Rates,              # Rates for first appearance
                             Rates - lag(Rates)) # Otherwise, Rates minus prior Rates
  ) %>% ungroup()    # Finally, ungroup the table

Upvotes: 1

Related Questions