R for循环:对于列中具有相同值的所有行组,执行

R for loop: For all groups of rows with the same value in column, do

我希望能得到一些帮助来理解在 R 中进行特定计算所需的语法。

我有一个这样的数据框:

a b c
1 1 0
2 1 1
3 1 0
4 2 0
5 2 0
6 3 1
7 3 0
8 3 0
9 4 0

并且我想创建一个新列 "d",当(且仅当)列 "c" 中的任何值都等于 1 时,该列的值为 1在列 "b." 中具有相同值的一组行否则(参见第 4,5 和 9 行)列 "d" 给出 0.

a b c d
1 1 0 1
2 1 1 1
3 1 0 1
4 2 0 0
5 2 0 0
6 3 1 1
7 3 0 1
8 3 0 1
9 4 0 0

这可以用 for 循环来完成吗?如果是这样,将不胜感激有关如何编写的任何建议。

使用data.table

setDT(df)
df[, d := as.integer(any(c == 1L)), b]

要在 base R 中执行此操作(使用与 dat.table 方法 any 相同的通用函数),您可以使用 ave:

df$d <- ave(cbind(df$c), df$b, FUN=function(i) any(i)==1)

由于您要求循环:

# adding the result col
dat <- data.frame(dat, d = rep(NA, nrow(dat)))

# iterate over group
for(i in unique(dat$b)){
  # chek if there is a one for 
  # each group
  if(any(dat$c[dat$b == i] == 1))
     dat$d[dat$b == i] <- 1
  else
    dat$d[dat$b == i] <- 0
}

当然 data.table 解决方案更优雅 ;)