R Aggregate FUN=head

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 05:26:16

问题


I would like to aggregate a table (tab) by two columns (sequence and program) to get the top row of samplesize (FUN=head).

sq <- c(1,1,1,1,1,1) 
prog<- c('A','A','B','B','C','C') 
ss <- c(47,47,28,28,47,47) 
tab<- data.frame(sq,prog,ss)

Aggregate is giving me an odd result in that if the sample size is the same for a DIFFERENT combination of sequence and program- it omits it.

agg  <- aggregate(cbind(sq,prog) ~ ss, data = tab, FUN=head,1,na.rm=TRUE)

I'm confused why this is occurring and why it is changing the program to a numerical sequence when it is text (A,B,C).


回答1:


It's because by default, data.frame creates a factor from character columns. You need:

tab <- data.frame(sq, prog, ss, stringsAsFactors = FALSE)

EDIT: I personally find the dplyr package very intuitive. For your result, I'd use:

library(dplyr)
tab %>%
  group_by(sq, prog) %>% 
  filter(row_number() == 1)


来源:https://stackoverflow.com/questions/48588890/r-aggregate-fun-head

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!