我有一个带有文本列name和因子的数据框city.它首先按字母顺序排序city然后name.现在我需要获得一个数据框,每个数据框中只包含第n个元素city,保持这种顺序.如何在没有循环的情况下以漂亮的方式完成?
我有:
name city
John Atlanta
Josh Atlanta
Matt Atlanta
Bob Boston
Kate Boston
Lily Boston
Matt Boston
Run Code Online (Sandbox Code Playgroud)
我想要一个函数,它返回第n个元素city,即如果它是第3个,那么:
name city
Matt Atlanta
Lily Boston
Run Code Online (Sandbox Code Playgroud)
它应该返回NULL,name如果它超出了所选的范围city,即第4:
name city
NULL Atlanta
Matt Boston
Run Code Online (Sandbox Code Playgroud)
请仅使用基础R?
在基地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)
Run Code Online (Sandbox Code Playgroud)
获取每个城市的第3项:
do.call(rbind,by(test,test$city,function(x) x[3,]))
Run Code Online (Sandbox Code Playgroud)
结果:
name city
Atlanta Matt Atlanta
Boston Lily Boston
Seattle <NA> <NA>
Run Code Online (Sandbox Code Playgroud)
为了得到你想要的东西,这里有一个小功能:
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)
}
Run Code Online (Sandbox Code Playgroud)
称之为:
nthrow(test,"city",3)
Run Code Online (Sandbox Code Playgroud)
结果:
name city
1 Matt Atlanta
2 Lily Boston
3 <NA> Seattle
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4252 次 |
| 最近记录: |