计算一个值在一个向量中出现了多少次[在R中有条件]

zengzsys  于 2023-04-03  发布在  其他
关注(0)|答案(3)|浏览(108)

我有下面的数据集,想计算在一个向量中某个条件发生了多少次:

structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L), Stimuli = c(1L, 0L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 
0L, 1L)), .Names = c("ID", "Stimuli"), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -12L), spec = structure(list(
    cols = structure(list(ID = structure(list(), class = 
c("collector_integer", 
    "collector")), Stimuli = structure(list(),
class = c("collector_integer", 
    "collector"))), .Names = c("ID", "Stimuli")), default = structure(list(),
class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

仅对每个ID单独计数,并且仅当Stimuli的值为1时。结果将在额外的一行中汇总,如下所示:

ID  Stimuli Count
1      1    1
1      0    0
1      0    0
1      1    2
2      1    1
2      1    2
2      0    0
2      1    3
3      0    0
3      1    1
3      0    0
3      1    2

我知道as.data.frame(table(df))用于获取频率,但在这种情况下,我想保留每行,并且只在每个ID序列中计数。

41ik7eoe

41ik7eoe1#

我们可以使用基于ifelse条件的group_by累积和(cumsum),其中“Stimuli”为1

library(dplyr)
d1 %>% 
   group_by(ID) %>% 
   mutate(Count = ifelse(Stimuli == 1, cumsum(Stimuli), 0))
# A tibble: 12 x 3
# Groups:   ID [3]
#      ID Stimuli Count
#   <int>   <int> <dbl>
# 1     1       1     1
# 2     1       0     0
# 3     1       0     0
# 4     1       1     2
# 5     2       1     1
# 6     2       1     2
# 7     2       0     0
# 8     2       1     3
# 9     3       0     0
#10     3       1     1
#11     3       0     0
#12     3       1     2

或者另一个选项是data.table

library(data.table)
setDT(df1)[Stimuli == 1, Count := seq_len(.N), by = ID][is.na(Count), Count := 0][]

或使用base R中的ave

with(d1, Stimuli *ave(Stimuli, ID, FUN = cumsum))
mklgxw1f

mklgxw1f2#

您可以使用data.table包:

library(data.table)
 setDT(df)[, Count := cumsum(Stimuli)*Stimuli, by=ID]

#     ID Stimuli Count 
#  1:  1       1     1 
#  2:  1       0     0 
#  3:  1       0     0 
#  4:  1       1     2 
#  5:  2       1     1 
#  6:  2       1     2 
#  7:  2       0     0 
#  8:  2       1     3 
#  9:  3       0     0 
# 10:  3       1     1 
# 11:  3       0     0 
# 12:  3       1     2
wr98u20j

wr98u20j3#

只使用基本的R,有点复杂。我将命名为df dat

dat1 <- dat
dat1$Count <- 0
sp <- split(dat1, dat1$ID)
res <- do.call(rbind, lapply(sp, function(x){
    inx <- x$Stimuli != 0
    x$Count[inx] <- cumsum(x$Stimuli[inx])
    x
}))
res

相关问题