How can I tie it in the same cust_cd so that L_num is displayed?
If the cust_cd is 1000401, it shows 9,4,11,11,4,4.
example:
cust_cd L_num
1000301 5,6,2,11,5
1000401 9,4,11,11,4,4
1000601 14,22,9,9,4
I can't do this. Please...
How can I tie it in the same cust_cd so that L_num is displayed?
If the cust_cd is 1000401, it shows 9,4,11,11,4,4.
example:
cust_cd L_num
1000301 5,6,2,11,5
1000401 9,4,11,11,4,4
1000601 14,22,9,9,4
I can't do this. Please...
You can do:
df_short <- data.frame(cust_cd = unique(df$cust_cd),
i_num = sapply(unique(df$cust_cd), function(i) {
paste(unique(df$i_num[which(df$cust_cd == i)]),
collapse = ", ")}))
df_short
#> cust_cd i_num
#> 1 1000101 18
#> 2 1000301 18
#> 3 1000401 9, 4, 11
#> 4 1000601 14, 22, 9
Data from question
df <- data.frame(cust_cd = c(rep(1000101, 7), 1000301, rep(1000401, 6),
rep(1000601, 5)),
i_num = c(rep(18, 8), 9, 4, 11, 11, 4, 4, 14, 22, 9, 9, 14))
df
#> cust_cd i_num
#> 1 1000101 18
#> 2 1000101 18
#> 3 1000101 18
#> 4 1000101 18
#> 5 1000101 18
#> 6 1000101 18
#> 7 1000101 18
#> 8 1000301 18
#> 9 1000401 9
#> 10 1000401 4
#> 11 1000401 11
#> 12 1000401 11
#> 13 1000401 4
#> 14 1000401 4
#> 15 1000601 14
#> 16 1000601 22
#> 17 1000601 9
#> 18 1000601 9
#> 19 1000601 14
Since you have not added any data, I have added the following sample data
> df
custid lnum
1 1 4
2 1 2
3 1 6
4 1 5
5 2 1
6 2 2
7 3 3
8 3 4
9 3 9
10 3 8
11 4 0
12 4 7
13 5 2
14 6 0
15 6 7
16 6 8
Proceed as
df %>% group_by(custid) %>%
mutate(d = paste(lnum, collapse = ", ")) %>%
select(-lnum) %>% slice_head()
custid d
<int> <chr>
1 1 4, 2, 6, 5
2 2 1, 2
3 3 3, 4, 9, 8
4 4 0, 7
5 5 2
6 6 0, 7, 8
We can use aggregate
from base R
aggregate(i_num ~ cust_cd, unique(df), FUN = toString)
# cust_cd i_num
#1 1000101 18
#2 1000301 18
#3 1000401 9, 4, 11
#4 1000601 14, 22, 9
df <- structure(list(cust_cd = c(1000101, 1000101, 1000101, 1000101,
1000101, 1000101, 1000101, 1000301, 1000401, 1000401, 1000401,
1000401, 1000401, 1000401, 1000601, 1000601, 1000601, 1000601,
1000601), i_num = c(18, 18, 18, 18, 18, 18, 18, 18, 9, 4, 11,
11, 4, 4, 14, 22, 9, 9, 14)), class = "data.frame", row.names = c(NA,
-19L))