2

我有一个带有 text 列name和 factor的数据框city。它按字母顺序首先 bycity然后name。现在我需要获取一个数据框,其中每个中仅包含第 n 个元素city,并保持此顺序。如何在没有循环的情况下以漂亮的方式完成?

我有:

name    city
John    Atlanta
Josh    Atlanta
Matt    Atlanta
Bob     Boston
Kate    Boston
Lily    Boston
Matt    Boston

我想要一个函数,它返回第 n 个元素city,即,如果它是第 3 个,那么:

name    city
Matt    Atlanta
Lily    Boston

如果超出选定的范围NULL,即第 4 次,它应该返回:namecity

name    city
NULL    Atlanta
Matt    Boston

请问只使用base R吗?

4

3 回答 3

5

在基础 R 中使用by

设置一些测试数据,包括一个额外的超出范围的值:

test <- read.table(text="name    city
John    Atlanta
Josh    Atlanta
Matt    Atlanta
Bob     Boston
Kate    Boston
Lily    Boston
Matt    Boston
Bob     Seattle
Kate    Seattle",header=TRUE)

获得每个城市的第 3 项:

do.call(rbind,by(test,test$city,function(x) x[3,]))

结果:

        name    city
Atlanta Matt Atlanta
Boston  Lily  Boston
Seattle <NA>    <NA>

为了得到你想要的,这里有一个小功能:

nthrow <- function(dset,splitvar,n) {
    result <- do.call(rbind,by(dset,dset[splitvar],function(x) x[n,]))
    result[,splitvar][is.na(result[,splitvar])] <- row.names(result)[is.na(result[,splitvar])]
    row.names(result) <- NULL
    return(result)
}

像这样称呼它:

nthrow(test,"city",3)

结果:

  name    city
1 Matt Atlanta
2 Lily  Boston
3 <NA> Seattle
于 2012-10-12T00:12:12.437 回答
3

一个data.table解决方案

library(data.table)
DT <- data.table(test)

# return all columns from the subset data.table
n <- 4
DT[,.SD[n,] ,by = city]
##      city name
## 1: Atlanta   NA
## 2:  Boston Matt
## 3: Seattle   NA

# if you just want the nth element of `name` 
# (excluding other columns that might be there)
# any of the following would work

DT[,.SD[n,] ,by = city, .SDcols = 'name']


DT[, .SD[n, list(name)], by = city]


DT[, list(name = name[n]), by = city]
于 2012-10-16T04:57:20.943 回答
2

您可以plyr为此使用:

dat <- structure(list(name = c("John", "Josh", "Matt", "Bob", "Kate", 

“百合”,“马特”),城市= c(“亚特兰大”,“亚特兰大”,“亚特兰大”,“波士顿”,“波士顿”,“波士顿”,“波士顿”)),.Names = c(“名称", "city"), class = "data.frame", row.names = c(NA, -7L))

library(plyr)

ddply(dat, .(city), function(x, n) x[n,], n=3)

> ddply(dat, .(city), function(x, n) x[n,], n=3)
  name    city
1 Matt Atlanta
2 Lily  Boston
> ddply(dat, .(city), function(x, n) x[n,], n=4)
  name   city
1 <NA>   <NA>
2 Matt Boston
> 

data.table使用base R or or sqldf...还有很多其他选项

于 2012-10-12T00:08:28.400 回答