R에 고유 한 조합과 빈도를 생성하는 솔루션이 있습니까?

Dec 09 2020

다음은 내 코드입니다. 나는 Food 열의 모든 반복되지 않는 조합을 생성하고 ID 열이 주어지면 몇 번이나 나타납니다.


customerDataFrame <- data.frame(CustomerID = c('A', 'B', 'B', 'C', 'D', 'D'),
                                Food = c('Pizza', 'Pizza', 'Tacos', 'Tacos', 'Tacos', 'Pizza'))

customerDataFrame %>% 
  group_by(CustomerID) %>% 
  summarise_all(funs(toString(unique(.)))) %>%
  ungroup() %>%
  group_by(Food) %>%
  summarise(n= n())

현재 출력은 다음과 같습니다.

# A tibble: 4 x 2
  Food             n
  <chr>        <int>
1 Pizza            1
2 Pizza, Tacos     1
3 Tacos            1
4 Tacos, Pizza     1

(Pizza, Tacos) 및 (Tacos, Pizza)를 구매하는 고객이 동일한 그룹에 속해야하므로 이는 기술적으로 잘못된 것입니다. 어떤 순서로 구매하든 상관 없습니다.

(이 답변에서 코드를 얻었습니다 : dplyr을 사용하여 주어진 그룹에 대한 고유 한 값 조합 벡터 만들기 )

내가 얻으려고하는 것은 다음과 같습니다.

# A tibble: 4 x 2
  Food             n
  <chr>        <int>
1 Pizza            1
2 Pizza, Tacos     2
3 Tacos            1

답변

3 Duck Dec 09 2020 at 21:15

이 시도. summarise()예상 결과를 얻으려면 두 배로 늘릴 수 있습니다 .

library(dplyr)
#Code
new <- customerDataFrame %>%
  arrange(CustomerID,Food)%>%
  group_by(CustomerID) %>%
  summarise(Food=paste0(Food,collapse = ',')) %>%
  group_by(Food,.drop = T) %>%
  summarise(N=n())

산출:

# A tibble: 3 x 2
  Food            N
  <chr>       <int>
1 Pizza           1
2 Pizza,Tacos     2
3 Tacos           1

다음을 사용하여 동일한 출력에 도달 할 수 있습니다 toString().

#Code 2
new <- customerDataFrame %>%
  arrange(CustomerID,Food)%>%
  group_by(CustomerID) %>%
  summarise(Food=toString(Food)) %>%
  group_by(Food,.drop = T) %>%
  summarise(N=n())
3 RonakShah Dec 09 2020 at 21:25

을 사용 toString sort하여 접을 때 Food.

library(dplyr)

customerDataFrame %>% 
  group_by(CustomerID) %>% 
  summarise(Food = toString(sort(Food))) %>%
  count(Food)

#   Food            n
#  <chr>        <int>
#1 Pizza            1
#2 Pizza, Tacos     2
#3 Tacos            1
akrun Dec 10 2020 at 03:33

에서는 다음 과 함께 base R사용할 수 있습니다 table.aggregate

table(aggregate(Food ~ CustomerID, 
   customerDataFrame[do.call(order, customerDataFrame),], FUN = toString)$Food)

#  Pizza Pizza, Tacos        Tacos 
#      1            2            1