R中的逻辑构建帮助

时间:2018-09-12 15:33:28

标签: r logic

我正在寻找在R中构建逻辑的帮助。我有一个数据集,如图中的图像Sample_Data set

对于任何给定的PackID

  1. 第一次出现cost=Rates
  2. 第二次出现cost = Rates[Current]- Rates[Previous]
  3. 第三次出现cost = Rates[Current]- Rates[Previous]

我尝试了下面的代码,但“费用”列保持不变。

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)

1 个答案:

答案 0 :(得分:1)

这是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