📜  如何找到R数据帧的列值的总和?

📅  最后修改于: 2022-05-13 01:54:46.142000             🧑  作者: Mango

如何找到R数据帧的列值的总和?

在本文中,我们将使用sum()函数在 R 中查找数据帧的列值的总和

句法:

创建数据框

可以使用 R 库中预定义的 data.frame()函数创建数据帧。此函数接受要创建的数据框所需的元素以及行数和列数。

以下是用于创建数据框的 R 程序:



R
# R Program to create a dataframe
  
# Creating a Data Frame
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print(df)


R
# Computing sum of column values
  
# Using sum() function
sum(df$row1)
sum(df$row2)


R
# R program to illustrate dataframe 
Roll_num = c(01, 02, 03)
Age = c(22, 25, 45)
Marks = c(70, 80, 90)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(Roll_num, Age, Marks) 
print(df)
  
# Computing Sum using sum() function
sum(df$Roll_num)
sum(df$Age)
sum(df$Marks)


R
# R program to illustrate dataframe 
ID = c(01, 02, 03)
Age = c(25, 30, 70)
Salary = c(70000, 85000, 40000)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(ID, Age, Salary) 
  
# Computing total salary
cat("Total Salary =", sum(df$Salary))


输出:

row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8

计算列值的总和

R 语言提供了一个内置函数sum()来计算数据帧的平均值。以下是用于实现sum()的 R 程序。

电阻

# Computing sum of column values
  
# Using sum() function
sum(df$row1)
sum(df$row2)

输出:

3
12

示例 2:

电阻

# R program to illustrate dataframe 
Roll_num = c(01, 02, 03)
Age = c(22, 25, 45)
Marks = c(70, 80, 90)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(Roll_num, Age, Marks) 
print(df)
  
# Computing Sum using sum() function
sum(df$Roll_num)
sum(df$Age)
sum(df$Marks)

输出:

6
92
240

示例 3:

电阻

# R program to illustrate dataframe 
ID = c(01, 02, 03)
Age = c(25, 30, 70)
Salary = c(70000, 85000, 40000)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(ID, Age, Salary) 
  
# Computing total salary
cat("Total Salary =", sum(df$Salary))

输出:

195000