将两行数值相加

huangapple go评论129阅读模式
英文:

Sum two rows with numeric values

问题

在这张图片中,我想将两个“乡村自治市”的值相加,使它们变成一个。我似乎不知道如何做到这一点。

英文:

In this picture, I want to add the values of the two "Rural municipality" to make them one. I don't seem to know how to do this.

table

答案1

得分: 0

这也可以使用基本的R实现。一种可能的方法是将要添加的行的区分字符串设置为相同的值,然后按照这个字符串进行聚合。

使用内置数据集的示例:

> s <- apply(Titanic, c("Class","Survived"), sum)
> x <- data.frame(Class=rownames(s), No=s[,"No"], Yes=s[,"Yes"])
> x$Class <- as.character(x$Class)
> x
     Class  No Yes
1st    1st 122 203
2nd    2nd 167 118
3rd    3rd 528 178
Crew  Crew 673 212

要组合(求和)1st和2nd类的两行,我们首先为它们分配一个新的相同的Class名称,然后按Class进行聚合:

> x[x$Class %in% c("1st","2nd"), "Class"] <- "upper"
> aggregate(. ~ Class, data=x, FUN=sum)
  Class  No Yes
1   3rd 528 178
2  Crew 673 212
3 upper 289 321
英文:

It is also possible with base R. One possible approach is to set the discriminating string of rows to be added to the same value and aggregate by this string.

Example with a builtin dataset:

&gt; s &lt;- apply(Titanic, c(&quot;Class&quot;,&quot;Survived&quot;), sum)
&gt; x &lt;- data.frame(Class=rownames(s), No=s[,&quot;No&quot;], Yes=s[,&quot;Yes&quot;])
&gt; x$Class &lt;- as.character(x$Class)
&gt; x
     Class  No Yes
1st    1st 122 203
2nd    2nd 167 118
3rd    3rd 528 178
Crew  Crew 673 212

To combine (sum) the two rows of 1st and 2nd class, we first assign them a new identical Class name, and then aggregate by Class:

&gt; x[x$Class %in% c(&quot;1st&quot;,&quot;2nd&quot;), &quot;Class&quot;] &lt;- &quot;upper&quot;
&gt; aggregate(. ~ Class, data=x, FUN=sum)
  Class  No Yes
1   3rd 528 178
2  Crew 673 212
3 upper 289 321

huangapple
  • 本文由 发表于 2023年7月12日 23:57:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定