df$row_sums <- 0
# Loop over each row
for (i in 1:nrow(df)) {
# Sum the values in each row starting from the second column
row_sum <- sum(df[i, 2:ncol(df)])
# Assign the row sum to the new column
df$row_sums[i] <- row_sum
}
# Add up the row sums to get the total sum of all row sums
total_row_sum <- sum(df$row_sums)
# Print the total sum of all row sums
cat("The total sum of all row sums is:", total_row_sum, "\n")
8条答案
按热度按时间f4t66c6m1#
sum
函数将所有数字相加,生成一个数字,而不是一个向量(至少不是长度大于1的向量)。看起来至少有一个列是一个因素。您可以通过检查以下内容将它们转换为数值向量
如果这看起来是对的
您可能必须先将它们转换为字符。在这种情况下
如果无法看到数据,很难判断应该执行哪一项操作。
一旦列是数字,你只需要做
mpbci0fu2#
这可用于忽略Excel工作表中的空白值。
我使用的是Euro stat数据集。
这个例子在R中运行:
gorkyyrv3#
你可以使用for循环:
q1qsirdb4#
第一种方式
第二种方式
shstlldc5#
可能有一两个列中包含因子,或者更有可能的是,您的列可能被格式化为因子。请尝试给予str(col1)和str(col2)。这应该可以告诉您这些列的格式。
我不确定你是想把一列的行加起来生成一个新列,还是只是把两列中的所有数字都加起来得到一个数字。
ekqde3dh6#
你可以这样做:
mspsb9vt7#
ejk8hzay8#
尝试将column3创建为表中column1 + column2的总和