首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >范畴内的条件计数

范畴内的条件计数
EN

Stack Overflow用户
提问于 2019-08-28 14:42:26
回答 3查看 63关注 0票数 1

在一组类别中,我试图计算一个真实数据集中有多少值在一组模拟值中,我想不出如何为它编写r代码,尽管我一直在使用dplyr。

代码语言:javascript
运行
复制
     Example: 

     category <-  c(1,1,1,1,2,2,2,2,3,3,3,3)
     dist <- c(50,20,50,50,70,70,50,50,50,50,70,70)
     type <- c("real", "sim", "sim","sim", "real", "sim", 
     "sim","sim","real", "sim", "sim","sim")

    df <- data.frame(category,dist,type)
    df


     category dist type
         1   50 real
         1   20  sim
         1   50  sim
         1   50  sim
         2   70 real
         2   70  sim
         2   50  sim
         2   50  sim
         3   50 real
         3   50  sim
         3   70  sim
         3   70  sim




What I want:

category count 
        1   2 
        2   1  
        3   1
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-09-16 17:13:07

上面的答案不是为我做的,但这可能是我在措辞上的错误。如果其他人有同样的问题,我发现下面的解决方案对我有效。

代码语言:javascript
运行
复制
    #getting values of a row

  sim <- subset(both, Type == "sim")
  snake <- subset(both, Type == "real")

  snake <- snake %>% slice(rep(1:n(), 1000)) ##1000 was the number of total simulated 
 animals I had

  count <- ifelse(snake$dist >= sim$dist, 1, ifelse(snake$dist < sim$dist,0,NA))
  count <- as.data.frame(count)
  count <- cbind(count, sim$category)
  colnames(count) <- c("binary", "category")
  head(count)

  totalB <- aggregate(binary~category, count, FUN = sum)
  names(totalB)[2] <- 'total'
  head(totalB)
票数 0
EN

Stack Overflow用户

发布于 2019-08-28 14:45:35

一个选项是group_by‘分类’和summarise,方法是检查'type‘sim的'dist’值小于'real‘类型的’

代码语言:javascript
运行
复制
library(dplyr)
df %>% 
   group_by(category) %>% 
   summarise(count = sum(unique(dist[type == 'sim']) <= dist[type == 'real'][1]))
票数 1
EN

Stack Overflow用户

发布于 2019-08-28 15:40:52

reshape2的一种方法,

代码语言:javascript
运行
复制
library(reshape2)

df2 <- as.data.frame(table(df))

my_cast <- dcast(df2,type~ category+dist,value.var="Freq")

col = apply(my_cast, 2, function(col) all(col !=0 ))

as.data.frame(t(my_cast[,col][2,]))


   # type sim
   # 1_50   2
   # 2_70   1
   # 3_50   1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57694976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档