Program Tip

dplyr / group_by를 사용하여 행 수 찾기

programtip 2020. 11. 27. 21:10
반응형

dplyr / group_by를 사용하여 행 수 찾기


mtcars데이터 세트를 사용하고 있습니다. 특정 데이터 조합에 대한 레코드 수를 찾고 싶습니다. count(*)SQL group by 절 과 매우 유사한 것 입니다. ddply()에서 plyr 나를 위해 노력하고 있습니다

library(plyr)
ddply(mtcars, .(cyl,gear),nrow)

출력 있음

  cyl gear V1
1   4    3  1
2   4    4  8
3   4    5  2
4   6    3  2
5   6    4  4
6   6    5  1
7   8    3 12
8   8    5  2

이 코드 사용

library(dplyr)
g <- group_by(mtcars, cyl, gear)
summarise(g, length(gear))

출력 있음

  length(cyl)
1          32

전달할 다양한 기능을 찾았 summarise()지만 아무것도 작동하지 않는 것 같습니다. 내가 찾은 함수 중 하나 sum(G)

Error in eval(expr, envir, enclos) : object 'G' not found

시도하여 n()반환하는,

Error in n() : This function should not be called directly

내가 도대체 ​​뭘 잘못하고있는 겁니까? 어떻게 얻을 수 group_by()/ summarise()나를 위해 작업에?


n()dplyr에는 (잠재적으로 그룹 내에서) 행을 계산 하는 특수 기능이 있습니다 .

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

그러나 dplyr는 count적은 타이핑으로 똑같은 기능을 하는 편리한 기능 도 제공합니다 .

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

또 다른 방법은 이중 콜론을 사용하는 것입니다.

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

Another option, not necesarily more elegant, but does not require to refer to a specific column:

mtcars %>% 
  group_by(cyl, gear) %>%
  do(data.frame(nrow=nrow(.)))

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

참고URL : https://stackoverflow.com/questions/22767893/find-number-of-rows-using-dplyr-group-by

반응형