我正在寻找在R中构建逻辑的帮助。我有一个数据集,如图中的图像
对于任何给定的Pack
和ID
:
cost=Rates
cost = Rates[Current]- Rates[Previous]
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)
答案 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