如何使用 tapply 之类的东西,但在 R 中保留其他列
How to use something like tapply but keeping other columns in R
假设我有这个数据框:
Date Value1 Value2
01-01 13.6 20
01-01 25.4 25
01-01 49.5 18
02-01 12.2 22
02-01 28.2 35
02-01 42.2 26
并且我只想保留此 table 中每个“日期”具有最小“Value1”的行,因此在这种情况下:
Date Value1 Value2
01-01 13.6 20
02-01 12.2 22
如果没有“Value2”列,我会使用 tapply(df$Value1, df$Date, min)
,但我想在我的摘要 table 中保留此列。你有什么简单的建议吗?我发现了不同的相似主题,但一直不明白如何适应我的情况。
按'Date'
分组后我们可以slice
library(dplyr)
df1 %>%
group_by(Date) %>%
slice(which.min(Value1))
或 filter
df1 %>%
group_by(Date) %>%
filter(Value1 == min(Value1))
在base R
中,这可以是ave
df1[with(df1, Value1 == ave(Value1, Date, FUN = min)),]
假设我有这个数据框:
Date Value1 Value2
01-01 13.6 20
01-01 25.4 25
01-01 49.5 18
02-01 12.2 22
02-01 28.2 35
02-01 42.2 26
并且我只想保留此 table 中每个“日期”具有最小“Value1”的行,因此在这种情况下:
Date Value1 Value2
01-01 13.6 20
02-01 12.2 22
如果没有“Value2”列,我会使用 tapply(df$Value1, df$Date, min)
,但我想在我的摘要 table 中保留此列。你有什么简单的建议吗?我发现了不同的相似主题,但一直不明白如何适应我的情况。
按'Date'
分组后我们可以slice
library(dplyr)
df1 %>%
group_by(Date) %>%
slice(which.min(Value1))
或 filter
df1 %>%
group_by(Date) %>%
filter(Value1 == min(Value1))
在base R
中,这可以是ave
df1[with(df1, Value1 == ave(Value1, Date, FUN = min)),]