R中两个或多个DataFrame列的总和
在本文中,我们将讨论如何在 R 编程语言中执行两个和多个数据帧列中的某些列。
使用中的数据库:
两列之和
必须计算总和的列可以通过$运算符调用,然后我们可以使用“+”运算符执行两个数据帧列的总和。
句法:
dataframe$column1 + dataframe$column2
在哪里
- 数据框是输入数据框
- column1 是数据框中的一列
- column2 是数据框中的另一列
示例: R 程序在数据框中添加两列
R
# create a dataframe with subjects marks
data=data.frame(sub1=c(90,89,78,89),
sub2=c(100,90,86,84),
sub3=c(89,90,98,99),
sub4=c(86,78,87,99))
# add column1 and column2
print(data$sub1 + data$sub2)
# add column1 and column3
print(data$sub1 + data$sub3)
# add column1 and column4
print(data$sub1 + data$sub4)
# add column2 and column4
print(data$sub2 + data$sub4)
Python3
# create a dataframe with subjects marks
data = data.frame(sub1=c(90, 89, 78, 89),
sub2=c(100, 90, 86, 84),
sub3=c(89, 90, 98, 99),
sub4=c(86, 78, 87, 99))
# add column1, column2 and column 4
print(rowSums(data[, c("sub1", "sub2", "sub4")]))
# add column1, column2 and column 3
print(rowSums(data[, c("sub1", "sub2", "sub3")]))
# add column4, column2 and column 3
print(rowSums(data[, c("sub4", "sub2", "sub3")]))
输出:
[1] 190 179 164 173
[1] 179 179 176 188
[1] 176 167 165 188
[1] 186 168 173 183
多列的总和
我们可以使用 rowSums() 和 c()函数计算多列的总和。我们只需要传递列的名称。
句法:
rowSums(dataframe[ , c(“column1”, “column2”, “column n”)])
在哪里
- 数据框是输入数据框
- c() 表示要指定添加的列数
示例: R 程序添加多列
蟒蛇3
# create a dataframe with subjects marks
data = data.frame(sub1=c(90, 89, 78, 89),
sub2=c(100, 90, 86, 84),
sub3=c(89, 90, 98, 99),
sub4=c(86, 78, 87, 99))
# add column1, column2 and column 4
print(rowSums(data[, c("sub1", "sub2", "sub4")]))
# add column1, column2 and column 3
print(rowSums(data[, c("sub1", "sub2", "sub3")]))
# add column4, column2 and column 3
print(rowSums(data[, c("sub4", "sub2", "sub3")]))
输出:
[1] 276 257 251 272
[1] 279 269 262 272
[1] 275 258 271 282