如何计算r中几个选定行的总和?
我有一个数据帧如何计算r中几个选定行的总和?,r,dataframe,sum,aggregate,R,Dataframe,Sum,Aggregate,我有一个数据帧df如下: id StateCode Year Data 1 AB123 AZ 1960 100 2 XY567 AZ 1961 200 3 CB666 AZ 1962 300 4 PT788 AZ 1963 400 5 AG999 AZ 1964 500 我想根据行ID获取df$Data的总和。例如,id“AB123”、id“C
df
如下:
id StateCode Year Data
1 AB123 AZ 1960 100
2 XY567 AZ 1961 200
3 CB666 AZ 1962 300
4 PT788 AZ 1963 400
5 AG999 AZ 1964 500
我想根据行ID获取df$Data
的总和。例如,id“AB123”、id“CB666”和id“XY567”的总和应返回600。我该怎么做?
谢谢 我们可以使用
id
上的%in%
过滤数据帧,然后对数据
列求和
sum(dat[dat$id %in% c("AB123", "CB666", "XY567"), ]$Data)
# [1] 600
数据
dat <- read.table(text = " id StateCode Year Data
1 AB123 AZ 1960 100
2 XY567 AZ 1961 200
3 CB666 AZ 1962 300
4 PT788 AZ 1963 400
5 AG999 AZ 1964 500",
header = TRUE, stringsAsFactors = FALSE)
dat我们可以使用id
上的%in%
过滤数据帧,然后对数据
列求和
sum(dat[dat$id %in% c("AB123", "CB666", "XY567"), ]$Data)
# [1] 600
数据
dat <- read.table(text = " id StateCode Year Data
1 AB123 AZ 1960 100
2 XY567 AZ 1961 200
3 CB666 AZ 1962 300
4 PT788 AZ 1963 400
5 AG999 AZ 1964 500",
header = TRUE, stringsAsFactors = FALSE)
dat我们可以用dplyr
library(dplyr)
df1 %>%
filter(id %in% c("AB123", "CB666", "XY567")) %>% #filter the rows
pull(Data) %>% #pull the column 'Data'
sum #get the sum
#[1] 600
我们可以使用dplyr
library(dplyr)
df1 %>%
filter(id %in% c("AB123", "CB666", "XY567")) %>% #filter the rows
pull(Data) %>% #pull the column 'Data'
sum #get the sum
#[1] 600
带基本R的单向:
ids <- c("AB123", "XY567", "CB666")
with(subset(df, id %in% ids), sum(Data))
#[1] 600
ids带基本R的单向:
ids <- c("AB123", "XY567", "CB666")
with(subset(df, id %in% ids), sum(Data))
#[1] 600
ids