当另一列中的值为X时,查找一列的最大值

use*_*537 3 r max

当C列的值= X时,如何找到一列(B列)的最大值.如何保留A列中的标签.假设我的数据名为my.data,a列=国家名,列b =出生的孩子数量和C列=孩子出生的年份.那么如何找到2001年出生的最大子女数量,保持国家的名称?

谢谢,我很抱歉,我是R的新手

mne*_*nel 5

R(以及有关SO的问题)有很多选项可用于执行此类操作

我会给出一个data.table解决方案,因为我喜欢这种查询的简单语法

data.table

为了大数据集的效率.我还为子集化提供了一种非常简单的语法.(.SD引用由iand 创建的子集by)

library(data.table)
DT <- data.table(my.data)
DT[year==2001, .SD[which.max(births)]]
Run Code Online (Sandbox Code Playgroud)

或者这是相同的,不需要.SD

DT[year==2001][which.max(births)]
Run Code Online (Sandbox Code Playgroud)

示例数据

my.data <- expand.grid(
  Country = c('Swaziland', 'Australia', 'Tuvalu', 'Turkmenistan'),
  year = 1990:2012 )
my.data$births <- rpois(nrow(my.data), lambda = 500)
DT <- data.table(my.data)
DT[year==2001, .SD[which.max(births)]]

##      Country year births
## 1: Swaziland 2001    501
Run Code Online (Sandbox Code Playgroud)

使用基数R.

births_2001 <- subset(my.data, year == 2001)
births_2001[which.max(births_2001$births),]

##      Country year births
## 45 Swaziland 2001    501
Run Code Online (Sandbox Code Playgroud)


Gle*_*n_b 5

有多种方法可以做到这一点。我会把它拆开,这样你就可以希望看到发生了什么更好的事情。

 my.data <- data.frame(
    country=c("Australia","France","Germany","Honduras","Nepal","Honduras"),
    children=c(120000,354000,380000,540000,370000,670000),
    year=c(2000,2001,2001,2002,2001,2003)
    )

 myd01 <- my.data[my.data$year==2001,]  # pulls out the 2001 data
 myd01[myd01$children==max(myd01$children),]  # finds the rows with the maximum 
Run Code Online (Sandbox Code Playgroud)