基于 R 数据框中列值的行总和
在本文中,我们将讨论如何在 R 编程语言中根据数据框中的列值汇总行值。假设你有一个这样的数据框: fruits shop_1 shop_2 1. Apple 1 13 2. Mango 9 5 3. Strawberry 2 14 4. Apple 10 6 5. Apple 3 15 6. Strawberry 11 7 7. Mango 4 16 8. Strawberry 12 8
该数据集由水果名称和 shop_1、shop_2 作为列名称组成。此处 shop_1 和 shop_2 显示商店中可用的水果数量。现在,您要查找 shope_1 中具有相同水果值的所有行的总和。所以我们的数据集看起来像这样: fruits shop_1 shop_2 1. Apple 14 34 2. Mango 13 21 3. Strawberry 25 29
方法一:使用聚合函数
聚合函数创建原始数据的子集,并为每个子集计算统计函数并返回结果。
句法:
aggregate(.~fruit,data=df,FUN=sum)
例子:
R
# Sum of rows based on column values
# Creating dataset
# creating fuits column
x <- c("Apple","Mango","Strawberry",
"Apple","Apple","Strawberry",
"Mango","Strawberry")
# creating shop_1 column
y <- c(1,9,2,10,3,11,4,12)
# creating shop_2 column
z <- c(13,5,14,6,15,7,16,8)
# creating dataframe
df <- data.frame(fruits=x,shop_1=y,shop_2=z)
# applying aggregate function
aggregate(.~fruits,data=df,FUN=sum)
R
# Sum of rows based on column values
# loading library
library(plyr)
# Creating dataset
# creating fuits column
x <- c("toy1","toy2","toy3",
"toy1","toy1","toy3",
"toy2","toy3")
# creating stock_1 column
y <- c(1,2,3,4,5,6,4,8)
# creating stock_2 column
z <- c(9,1,10,5,2,6,4,8)
# creating dataframe
df <- data.frame(toys=x,stock_1=y,stock_2=z)
# using sum function colwise
ddply(df,"toys",numcolwise(sum))
输出:
方法二:使用ddply和numcolwise函数
ddply简单地分割给定的数据帧和PE R型在其上的任何操作(可能应用一个函数),并返回该数据帧。
colwise是一个函数 著名的 胶合板 包。 colwise福NCTI上被用于计算在数据EA] C H列的函数 框架,它按列计算。
例子:
电阻
# Sum of rows based on column values
# loading library
library(plyr)
# Creating dataset
# creating fuits column
x <- c("toy1","toy2","toy3",
"toy1","toy1","toy3",
"toy2","toy3")
# creating stock_1 column
y <- c(1,2,3,4,5,6,4,8)
# creating stock_2 column
z <- c(9,1,10,5,2,6,4,8)
# creating dataframe
df <- data.frame(toys=x,stock_1=y,stock_2=z)
# using sum function colwise
ddply(df,"toys",numcolwise(sum))
输出: