[英]Put column sums in a new row in a matrix
I have a data frame that consists of municipality names (factors) in the first column and number of projects (integers) in columns two and three. 我有一个数据框,其中第一列包含市政名称(要素),第二和第三列包含项目数量(整数)。
Var.1<-c("Andover", "Avon", "Bethany")
Freq.x<-c(2,NA,10)
Freq.y<-c(4,2,9)
Projects<-data.frame(Var.1,as.integer(as.numeric(Freq.y)),as.integer(as.numeric(Freq.x)))
[Note: I am making the second and third columns as integers here because that's how they are categorized in my actual data set.] [注意:我在这里将第二和第三列作为整数,因为这是我在实际数据集中对其进行分类的方式。]
I was able to take the row sums of the rows using: 我能够使用以下方法获取行的总和:
Projects$Sum<-rowSums(Projects[,2:3])
However, I'm unable to figure out how to take the column sums. 但是,我无法弄清楚如何获取列总和。 I tried using the following formula: 我尝试使用以下公式:
Projects[Total,]<-colSums(Projects[2:3,])
I get the error: 我得到错误:
Error in colSums(Projects[2:3, ]) : 'x' must be numeric colSums(Projects [2:3,])中的错误:“ x”必须为数字
Even when I convert the second and third columns to as.numeric
, I get the same response. 即使将第二和第三列转换为as.numeric
,我as.numeric
得到相同的响应。
Can someone advise how to obtain the column sums create a new row at the bottom which will house the results? 有人可以建议如何获取列总和吗?在底部创建一个新行来容纳结果?
You can do something like this: 您可以执行以下操作:
Var.1<-c("Andover", "Avon", "Bethany")
Freq.x<-c(2,NA,10)
Freq.y<-c(4,2,9)
freq <- cbind(Freq.x, Freq.y)
freq <- rbind(freq, colSums(freq, na.rm=TRUE))
Projects <- data.frame(name=c(Var.1, "Total"), freq)
In particular: keep numeric part separate and compute it's sums; 特别是:将数字部分分开并计算其和; add "TOtal" to the character vector before it will be converted to factor, and thereafter make the data.frame 在字符向量上将“总计”添加到字符向量之前,将其转换为因数,然后生成data.frame
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.