How to sum a column in R

Asked

Viewed 673 times

1

I am using a database with several dates and would like to sum up the values of the last available date, I can filter the data.frame by date, but I can’t make the sum of the values, I’m trying to use the function colSums.

Database link used in csv: https://covid.saude.gov.br/

Code I’m using:

library(tidyverse)

dados <- read_delim("~/Downloads/arquivo_geral.csv", 
                                        ";", escape_double = FALSE, trim_ws = TRUE)
dados <- dados[,-c(1,4,6)]

soma <- dados %>%
  filter(data == max(dados$data)) %>%
  select(-grep("obitosAcumulados", colnames(dados))) %>%
  colSums(dados[3])

2 answers

2


Just insert the function summarize:

library(tidyverse)

dados %>%
  filter(data == max(dados$data)) %>%
  select(-grep("obitosAcumulados", colnames(dados))) %>%
  summarise(var = colSums(dados[3]))

# A tibble: 1 x 1
#      var
#    <dbl>
# 1 550237

And if the goal is just to add up the column, you don’t have to create an object (soma) for that reason.

2

Using colSums() or rowSums() in this case would not work, because according to the function documentation, objects must have two or more dimensions... So, when you try to pass the column array obitAcumulated, you are putting as input a series (an object with a single dimension).

I managed to reach the result that you search doing the following:

require(dplyr)

df <- read.csv('Seu Diretório\\seu_arquivo.csv', sep = ';')

# Utilizei o arquivo do link que enviou.

soma <- df %>% 
  select(data, obitosAcumulados) %>% 
  filter(data == '2020-04-22') # Para esta linha de código funcionar, a coluna data 
                               # precisa ser um Fator.

soma <- sum(soma$obitosAcumulados)  # O resultado será o total somado de todas
                                    # as ocorrências do dia utilizado como filtro.

I hope I helped achieve the expected result, let us know if it has been resolved. Any doubt calls again.

  • Thanks for the solution, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.