首页 > 解决方案 > 返回 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 个。我怎样才能使这成为可能。欢迎任何建议。

标签: r

解决方案


如果我们想要前五个,请使用 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 

推荐阅读