我有这样的数据框
#dt
# a b c
#1: a 1 d
#2: a 1 d
#3: b 0 b
#4: b 1 d
#5: b 0 b
我想要接收的是具有满足以下条件的每行行数的带有计数器的columnt:b = 1和c = d
#dt
# a b c counter
#1: a 1 d 2
#2: a 1 d 2
#3: b 0 d 1
#4: b 1 d 1
#5: b 0 b 0
有什么想法怎么做?
答案 0 :(得分:2)
尝试一下:
library(dplyr)
dt = data.frame(a = c("a","a","b","b","b"),
b= c(1,1,0,1,0),
c = c("d","d","b","d","b"))
dt <- dt %>%
mutate(counter = (b == 1) +( c == "d") )
答案 1 :(得分:0)
我使用了@FALL Gora答案
dt %>% mutate(counter = as.numeric(((b == 1) & ( c == "d"))))
但我已经添加
dt %>% group_by(a) %>% mutate(counter1=sum(counter))
现在可以使用