Home > Net >  Add the zeroes of columns up in a new row in R
Add the zeroes of columns up in a new row in R

Time:05-20

I have a dataset of clusterings like this:

subjects   `1`   `2`   `3`
"A"         0     1     1
"B"         1     1     0
"C"         0     1     0
"D"         0     1     1

I want to add a row to this data so I can understand how the clusterings split the data. So I want a data.frame like this:

subjects   `1`   `2`   `3`
"A"         0     1     1
"B"         1     1     0
"C"         0     1     0
"D"         0     1     1
grp1        3     0     2

How can I do this?

CodePudding user response:

There's probably a function for this (something along the lines of https://www.rdocumentation.org/packages/janitor/versions/2.1.0/topics/adorn_totals) but you could also potentially do it yourself using:

library(dplyr)
library(purrr)

df <- structure(list(subjects = c("A", "B", "C", "D"),
                     `1` = c(0, 1, 0, 0), 
                     `2` = c(1, 1, 1, 1), 
                     `3` = c(1, 0, 0, 1)), 
                class = c("tbl_df", "tbl", "data.frame"),
                row.names = c(NA, -4L))

col_totals <- map_df(df[,-1], ~sum(. == 0))
col_totals$subjects <- "grp1"
bind_rows(df, col_totals)
#> # A tibble: 5 × 4
#>   subjects   `1`   `2`   `3`
#>   <chr>    <dbl> <dbl> <dbl>
#> 1 A            0     1     1
#> 2 B            1     1     0
#> 3 C            0     1     0
#> 4 D            0     1     1
#> 5 grp1         3     0     2

Created on 2022-05-20 by the reprex package (v2.0.1)

CodePudding user response:

You can also use add_row:

df %>%
   add_row(subjects = 'grp1', !!!colSums(!.[-1]))

# A tibble: 5 x 4
  subjects   `1`   `2`   `3`
  <chr>    <dbl> <dbl> <dbl>
1 A            0     1     1
2 B            1     1     0
3 C            0     1     0
4 D            0     1     1
5 grp1         3     0     2
  •  Tags:  
  • r
  • Related