计算data.frame中两个变量的组合

时间:2018-01-23 13:50:42

标签: r combinations

我有两个data.frames - g包含两个变量的所有可能(此处:8个)组合,h包含对8个组合中的任意一个的62个观察值dput()在底部)。

我已向g添加了第三列,该列应该采用h中每个组合的观察计数:

> g
  where what days
1    sg free    0
2    in free    0
3    hk free    0
4    de free    0
5    sg work    0
6    in work    0
7    hk work    0
8    de work    0

我想计算gh中的每个组合出现在for( i in seq( nrow( g ) ) ) for( j in seq( nrow( h ) ) ) if( all( g[ i, 1:2 ] == h[ j, ] ) ) g[ i, 3 ] <- g[ i, 3 ] + 1 中的频率,现在使用老式的嵌套循环运行良好:

> g
  where what days
1    sg free   10
2    in free    0
3    hk free    4
4    de free    4
5    sg work   18
6    in work   10
7    hk work    6
8    de work   10

给了我想要的东西:

g <- structure(list(where = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L), .Label = c("sg", "in", "hk", "de"), class = "factor"), what = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("free", "work"), class = "factor"), 
days = c(0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("where", "what", 
"days"), out.attrs = structure(list(dim = c(4L, 2L), dimnames = structure(list(
Var1 = c("Var1=sg", "Var1=in", "Var1=hk", "Var1=de"), Var2 = c("Var2=free", 
"Var2=work")), .Names = c("Var1", "Var2"))), .Names = c("dim", "dimnames")), 
row.names = c(NA, -8L), class = "data.frame")

h <- structure(list(values = c("sg", "sg", "sg", "sg", "sg", "sg", 
"sg", "sg", "sg", "sg", "sg", "sg", "sg", "sg", "in", "in", "in", 
"in", "in", "hk", "hk", "hk", "hk", "hk", "de", "de", "de", "de", 
"de", "de", "de", "sg", "sg", "sg", "sg", "sg", "sg", "sg", "sg", 
"sg", "sg", "sg", "sg", "sg", "sg", "in", "in", "in", "in", "in", 
"hk", "hk", "hk", "hk", "hk", "de", "de", "de", "de", "de", "de", 
"de"), values.1 = c("free", "work", "work", "work", "work", "free", 
"free", "work", "work", "work", "work", "work", "free", "free", 
"work", "work", "work", "work", "work", "free", "free", "work", 
"work", "work", "work", "work", "free", "free", "work", "work", 
"work", "free", "work", "work", "work", "work", "free", "free", 
"work", "work", "work", "work", "work", "free", "free", "work", 
"work", "work", "work", "work", "free", "free", "work", "work", 
"work", "work", "work", "free", "free", "work", "work", "work"
)), .Names = c("values", "values.1"), row.names = c(NA, -62L), class = "data.frame")

但我想知道是否有更少的神秘,更简洁的方法;我特别好奇基地R是否提供了我尚未发现的工具。

数据:

public class Order : FullAuditedEntity
{
    public virtual ICollection<OrderDetail> Details { get; set; }
}

public class OrderDetail : FullAuditedEntity
{
    [ForeignKey("OrderId")]
    public virtual Order Order { get; set; }
    public int OrderId { get; set; }
}

1 个答案:

答案 0 :(得分:1)

这有一个简单的整洁解决方案。我更改了h中的列名称以匹配g中的列名(where和what)。按两个值进行分组并总结 - 这将给出组合的计数。然后,做一个left_join回到g并且你有你的计数。

library(dplyr)

h_s = h %>% 
  group_by(where,what) %>% 
  summarise(days=n())

g %>% 
  left_join(h_s,by=c("where","what")) %>% 
  select(where,what,days=days.y) %>%
  mutate(days = ifelse(is.na(days),0,days))

修改

左连接的原因是确保表示在h中找不到的任何情况。我添加了一个mutate来将缺失值转换为0。