Home > Blockchain >  Grouping variables and adding them to the end of the table
Grouping variables and adding them to the end of the table

Time:11-30

I have a table that looks like the following:

Type Number
A 1
B 2
E 3
C 4
D 5
C 6
G 7

I would like to make a table where I group Types (A-C) and add these same observations to the bottom of the table. So the new table would look like:

Type Number
A 1
B 2
E 3
C 4
D 5
C 6
G 7
A-C 1
A-C 2
E 3
A-C 4
D 5
A-C 6
G 7

Is this possible? Any help would be much appreciated!

CodePudding user response:

One option would be to work out your groupings then bind the two dataframes together, e.g.

library(dplyr)

df <- read.table(text = "Type   Number
A   1
B   2
E   3
C   4
D   5
C   6
G   7", header = TRUE)

tmp <- df %>%
  mutate(Type = ifelse(Type %in% c("A", "B", "C"),
                       "A-C", Type))
result <- bind_rows(df, tmp)
result
#>    Type Number
#> 1     A      1
#> 2     B      2
#> 3     E      3
#> 4     C      4
#> 5     D      5
#> 6     C      6
#> 7     G      7
#> 8   A-C      1
#> 9   A-C      2
#> 10    E      3
#> 11  A-C      4
#> 12    D      5
#> 13  A-C      6
#> 14    G      7

Created on 2022-11-30 with reprex v2.0.2


Same approach but with base R (i.e. don't need the dplyr package):

df <- read.table(text = "Type   Number
A   1
B   2
E   3
C   4
D   5
C   6
G   7", header = TRUE)

tmp <- df
tmp$Type <- ifelse(df$Type %in% c("A", "B", "C"), "A-C", df$Type)
rbind(df, tmp)
#>    Type Number
#> 1     A      1
#> 2     B      2
#> 3     E      3
#> 4     C      4
#> 5     D      5
#> 6     C      6
#> 7     G      7
#> 8   A-C      1
#> 9   A-C      2
#> 10    E      3
#> 11  A-C      4
#> 12    D      5
#> 13  A-C      6
#> 14    G      7

Created on 2022-11-30 with reprex v2.0.2

CodePudding user response:

Using forcats factor collapse:

library(forcats)

rbind(df, transform(df, Type = fct_collapse(Type, `A-C` = c("A", "B", "C"))))
#    Type Number
# 1     A      1
# 2     B      2
# 3     E      3
# 4     C      4
# 5     D      5
# 6     C      6
# 7     G      7
# 8   A-C      1
# 9   A-C      2
# 10    E      3
# 11  A-C      4
# 12    D      5
# 13  A-C      6
# 14    G      7
  •  Tags:  
  • r
  • Related