I assume that this is because one of the columns has character format, but I don't know how to include it in the proposed solution: dat1 [nrow (dat1) + 1,] <- colSums (dat1).
Can you please provide a small sample of your dataset which produces the issue you encounter? This helps us to better understand and provide a solution for your issue.
You can do it like below.
However, I have to mention that there are better and more robust ways of doing column manipulation, especially when your real dataset is not as simple as this one.
library(dplyr)
## create sample dataframe
df <- tribble(
~a, ~b, ~c, ~d, ~e, ~f, ~g,
"men", 27, 56, 87, 32, 0, 5,
"women", 0, 0, 20, 21, 12, 5,
)
df
#> # A tibble: 2 x 7
#> a b c d e f g
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 men 27 56 87 32 0 5
#> 2 women 0 0 20 21 12 5
## get totals from column 2 onwards
row_totals <- colSums(df[,2:NCOL(df)])
## append row with totals
df[nrow(df) + 1, ] <- c(a = "totals", as.list(row_totals))
df
#> # A tibble: 3 x 7
#> a b c d e f g
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 men 27 56 87 32 0 5
#> 2 women 0 0 20 21 12 5
#> 3 totals 27 56 107 53 12 10
I don't know if you're familiar with the R for Data Science book, otherwise you might be interested in chapter 5 Data transformation:
Visualisation is an important tool for insight generation, but it is rare that you get the data in exactly the right form you need. Often you’ll need to create some new variables or summaries, or maybe you just want to rename the variables or reorder the observations in order to make the data a little easier to work with. You’ll learn how to do all that (and more!) in this chapter [..]
You could also try the adorn_totals function from the janitor package
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(janitor)
#>
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#>
#> chisq.test, fisher.test
df <- tribble(
~a, ~b, ~c, ~d, ~e, ~f, ~g,
"men", 27, 56, 87, 32, 0, 5,
"women", 0, 0, 20, 21, 12, 5,
)
df
#> # A tibble: 2 x 7
#> a b c d e f g
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 men 27 56 87 32 0 5
#> 2 women 0 0 20 21 12 5
df %>% adorn_totals()
#> a b c d e f g
#> men 27 56 87 32 0 5
#> women 0 0 20 21 12 5
#> Total 27 56 107 53 12 10