根据嵌套for循环中的条件创建新列

fli*_*ngs 1 for-loop nested r subset lapply

我正在尝试在我的数据集中创建一个新列,告诉我产品的所有3个月的收入是0,所有3个月都是0,或者3个月都没有0.

我提供NewColumn了我想要的结果.

data$ZEROES <- 0
data$ZEROES2 <- 0
for (i in unique(data$product_id)){
    for (j in unique(data$Revenue)){
        n[j] <-ifelse(all(data$Value == 0)," ALL 0", 
        ifelse(any(data$Value == 0),"Some 0", 
        ifelse(all(data$Value != 0), "None 0", "Blank")))
    data$ZEROES[j] <-n[j]
    data$ZEROES2[i] <-long$ZEROES[j]
    }
} 

product_ id Date         Revenue           Value    NewColumn
1           January       in               0           Some 0   
1           February      in               1           Some 0 
1           March         in               0           Some 0 
1           January       out              0           All 0 
1           February      out              0           All 0 
1           March         out              0           All 0 
2           January       in               1           No 0 
2           February      in               2           No 0 
2           March         in               3           No 0 
2           January       out              1           Some 0 
2           February      out              1           Some 0 
2           March         out              0           Some 0 
Run Code Online (Sandbox Code Playgroud)

数据

structure(list(product_id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L),
               Date = c("January", "February", "March", "January", "February", "March", "January", "February", "March", "January", "February", "March"),
               Revenue = c("in", "in", "in", "out", "out", "out", "in", "in", "in", "out", "out", "out"),
               Value = c(0L, 1L, 0L, 0L, 0L, 0L, 1L, 2L, 3L, 1L, 1L, 0L),
               NewColumn = c("Some 0",  "Some 0", "Some 0", "All 0", "All 0", "All 0", "No 0", "No 0",  "No 0", "Some 0", "Some 0", "Some 0")),
          .Names = c("product_id",  "Date", "Revenue", "Value", "NewColumn"),
          class = "data.frame", row.names = c(NA, -12L))
Run Code Online (Sandbox Code Playgroud)

the*_*ail 5

在基础R中,您可以创建自定义函数,然后用于ave在每个组中进行计算:

f <- function(x) if(all(x)) 3 else if(any(x)) 2 else 1
c("None","Some","All")[with(dat, ave(Value==0, list(product_id,Revenue), FUN=f))]
# [1] "Some" "Some" "Some" "All"  "All"  "All"  "None" "None" "None" "Some"
#[11] "Some" "Some"
Run Code Online (Sandbox Code Playgroud)