在聚合函数中显示多列,包括R中的字符串/字符

在聚合函数中显示多列,包括R中的字符串/字符,r,dataframe,subset,R,Dataframe,Subset,这里没有问题 假设我有这个数据框: City State Pop Fresno CA 494 San Franciso CA 805 San Jose CA 945 San Diego CA 1307 Los Angeles CA 3792 Reno NV 225 Henderson NV 257 Las Vegas NV 583 Gresham

这里没有问题

假设我有这个数据框:

City          State Pop
Fresno          CA  494
San Franciso    CA  805
San Jose        CA  945
San Diego       CA  1307
Los Angeles     CA  3792
Reno            NV  225
Henderson       NV  257
Las Vegas       NV  583
Gresham         OR  105
Salem           OR  154
Eugene          OR  156
Portland        OR  583
Fort Worth      TX  741
Austin          TX  790
Dallas          TX  1197
San Antonio     TX  1327
Houston         TX  2100
我想得到每个州每三分之一的最低人口,这将有:

City         State  Pop
San Jose        CA  945
Las Vegas       NV  583
Eugene          OR  156
Dallas          TX  1197
我试过这个:

ord_pop_state <- aggregate(Pop ~ State  , data = ord_pop, function(x) { x[3] } )
State  Pop
 CA  945
 NV  583
 OR  156
 TX 1197

为了获得包括城市在内的所需输出,我在这方面缺少什么?

我建议尝试使用
data.table
包来完成这类任务,因为语法更简单,代码更高效。我还建议添加
order
函数,以确保数据已排序

library(data.table)
setDT(ord_pop)[order(Pop), .SD[3L], keyby = State]
#    State      City  Pop
# 1:    CA  San Jose  945
# 2:    NV Las Vegas  583
# 3:    OR    Eugene  156
# 4:    TX    Dallas 1197
因此,基本上,首先数据按
Pop
排序,然后我们按
状态将
.SD
(数据本身的符号参数)子集化


虽然这也可以用base R轻松解决(我们假设数据在这里排序),但我们可以只为每个组创建一个索引,然后根据该索引创建一个简单的子集

ord_pop$indx <- with(ord_pop, ave(Pop, State, FUN = seq))
ord_pop[ord_pop$indx == 3L, ]
#         City State  Pop indx
# 3   San Jose    CA  945    3
# 8  Las Vegas    NV  583    3
# 11    Eugene    OR  156    3
# 15    Dallas    TX 1197    3

ord\u pop$indx这是一个
dplyr
版本:

df2 <- df %>%
    group_by(state) %>% # Group observations by state
    arrange(-pop) %>% # Within those groups, sort in descending order by pop
    slice(3) # Extract the third row in each arranged group

在R中,使用不同的包可以获得相同的最终结果。包的选择是代码效率和简单性之间的权衡

由于您来自强大的SQL背景,这可能更易于使用:

library(sqldf)

#Example to return 3rd lowest population of a State
result <-sqldf('Select City,State,Pop from data order by Pop limit 1 offset 2;')

#Note the SQL query is a sample and needs to be modifed to get desired result.
库(sqldf)
#返回州第三低人口的示例

结果可能
slice(3)
summary
好,这也会保留城市名称。谢谢。@ulfelder:谢谢你的回答。但我不想使用dplyr包,而只是暂时使用基本包。我的选择是什么?@DavidArenburg已经介绍过你了。这是一个很好的答案,大卫。但我不想使用我拥有的默认包以外的包。谢谢你的快速回答。我提供了一个bse R替代方案。。。你没看见吗?对不起,我没看见。我会试试那个,过会儿再来找你。谢谢你,大卫,你做对了。这基本上是一个细分问题。顺便问一下,ave()在这里是如何工作的?我理解(如果正确的话)用于获取平均值?
ave
mean
作为其默认函数,但您可以使用
FUN
参数覆盖它(就像我所做的那样)。顺便说一句,这不是聚合操作,而只是子集。
> df2
Source: local data frame [3 x 3]
Groups: state

  state city  pop
1     A    b 1018
2     B    b 1049
3     C    b 1039
library(sqldf)

#Example to return 3rd lowest population of a State
result <-sqldf('Select City,State,Pop from data order by Pop limit 1 offset 2;')

#Note the SQL query is a sample and needs to be modifed to get desired result.