【问题标题】:Add an incremental counter to a dataframe in R将增量计数器添加到 R 中的数据帧
【发布时间】:2021-05-05 22:21:09
【问题描述】:

我有一个由 3 列组成的数据框,第三列(“V3”)包含实验期间出现的标记的名称。 我想添加另一列,告诉我每个标记在该实例之前该特定标记出现了多少次。 我没有使用 tidyverse 在 R 中完成了它,但它非常耗时,我想知道你是否可以帮助我使用 tidyverse。

目前我的脚本是这样的:

data$counter <- NA
x<-1
for (i in 1:nrow(data)){
 if ((str_detect(data$V3[i], 'NEGATIVE'))==TRUE){
  data$counter[i] <- x
  x <- x +1
 }
}

【问题讨论】:

  • 您可以使用dput(data) 发布您的数据吗?

标签: r tidyverse


【解决方案1】:

我认为cumsum 会在这里做得很好:

testdata <- data.frame(V3=sample(c("NEGATIVEsomething","others"),50,replace=TRUE), stringsAsFactors = FALSE)

negatives <- grepl("NEGATIVE",testdata$V3)
negatives <- as.numeric(negatives)
negatives <- cumsum(negatives)
negatives[negatives == 0] <- NA

testdata$counter <- negatives

编辑:由于您想在找到“NEGATIVE”后增加计数器并将旧计数器放在该位置,因此您应该使用

negatives <- cumsum(negatives)-1

然后删除开头的0-1 计数:

negatives[negatives  %in% c(0,-1)] <- NA 

【讨论】:

  • 刚要推荐cumsum
【解决方案2】:

您可以使用group_by() 执行此操作,然后使用seq_along() 生成计数器。

库(dplyr)

data %>%
  group_by(V3) %>%
  mutate(counter = seq_along(V3)) %>%
  ungroup()

【讨论】:

    【解决方案3】:

    试试

    data$counter <- cumsum((str_detect(data$V3, 'NEGATIVE')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2021-09-12
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      相关资源
      最近更新 更多