r - 返回 R 中前五列的函数
问题描述
我在 R 中编写了一个函数,它应该返回输入最多的前五个开发人员:
developer.busy <- function(x){
bus.dev <- sort(table(test2$devf), decreasing = TRUE)
return(bus.dev)
}
bus.dev(test2)
ericb shields mdejong cabbey lord elliott-oss jikesadmin coar
3224 1432 998 470 241 179 77 1
目前它只是打印出按递减范围排序的所有开发人员。我只想显示前 5 个。我怎样才能使这成为可能。欢迎任何建议。
解决方案
如果我们想要前五个,请使用 index with[
或 with head
。用三个输入修改函数,数据对象名称,列名称('colnm')和要提取的元素数('n')
developer.busy <- function(data, colnm, n){
sort(table(data[[colnm]]), decreasing = TRUE)[seq_len(n)]
# or another optioin is
head(sort(table(data[[colnm]]), decreasing = TRUE), n)
}
developer.busy(test2, "developerf", n = 5)
mtcars
- 使用带有数据集的可重现示例
data(mtcars)
developer.busy(mtcars, 'carb', 5)
# 2 4 1 3 6
#10 10 7 3 1
推荐阅读
- repast-simphony - Repast:如何直接从代码而不是 GUI 添加和设置新参数
- javascript - 在旧 json 数据中应用数学后生成新的 json 数据
- html - 如何修复无法绑定到 formControl 错误
- mongodb - 带有项目的 MongoDB 组
- sql - 子查询作为联接?
- javascript - 拆分 csv 行并转换数值(Typescript、Javascript)
- javascript - JS 数组 — 将 1D 数组重新组织为 N 组的 2D 数组,按顺序放置值
- c++ - MSVC 中从 _Ty 到 int 警告的转换累积
- amazon-ec2 - 为什么选择 RDS/Aurora 而不是 AWS 上的 EC2 实例,或者选择 CloudSQL 而不是 Compute Engine (VM) 作为数据库服务器?
- controller - 在 Hybris 中扩展控制器加速器服务