我创建了一个带有计数,N和百分比的摘要data.frame。 摘要data.frame具有名称 - >类别,n,计数和百分比。 计数data.frame具有名称 - >类别,数量。 类别是角色。通常,计数数据框中的行将小于汇总中的行。
我在MSSQL中这样做的方式是
update summary
set summary.count = counts.count
from summary
inner join counts
on summary.category = counts.category
怎么可以在R?
中完成支持代码。
summary <- data.frame(category=c("apples","oranges","pears"),N=10,count=0,percentage=0)
> summary
category N count percentage
1 apples 10 0 0
2 oranges 10 0 0
3 pears 10 0 0
> counts <- data.frame( category=c("apples","pears"), count = c(5,5) )
> counts
category count
1 apples 5
2 pears 5
# desired outcome after processing
> summary
category N count percentage
1 apples 10 5 0.5
2 oranges 10 0 0
3 pears 10 5 0.5
答案 0 :(得分:0)
我在搜索R data.frame union之后发现了merge命令。
> summary <- data.frame(category=c("apples","oranges","pears"),N=10)
> summary
category N
1 apples 10
2 oranges 10
3 pears 10
> counts <- data.frame( category=c("apples","pears"), count = c(5,5) )
> counts
category count
1 apples 5
2 pears 5
> merged <- merge( summary, counts, by="category", all.x = TRUE)
> merged
category N count
1 apples 10 5
2 oranges 10 NA
3 pears 10 5
> merged[is.na(merged)] <- 0
> merged
category N count
1 apples 10 5
2 oranges 10 0
3 pears 10 5
> merged["percentage"] = merged$count / merged$N
> merged
category N count percentage
1 apples 10 5 0.5
2 oranges 10 0 0.0
3 pears 10 5 0.5
要查看合并映射到SQL连接的概述,请参阅How to join (merge) data frames (inner, outer, left, right)?