【发布时间】:2016-10-27 16:12:12
【问题描述】:
我正在尝试在我的数据集中创建一个新列,用于告诉我产品的收入是否在 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
数据
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))
【问题讨论】:
-
上帝禁止人们将您在答案中使用的数据添加给他人
-
好电话,我通常会尝试包含它(作为对 OP 的提醒)但这次忘记了,我很高兴@flightless13wings 注意到了:-)
-
感谢 @rawr 编辑我最初的问题并添加数据。
-
其中一个答案是否解决了您的问题?如果是这样,通常通过选中答案左侧的复选标记来接受答案。
标签: r for-loop nested subset lapply