英文:
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.
答案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:
> 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
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:
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论