How to sum a column in R

I am using a database with multiple dates and would like to sum the values of the last available date, I can filter the data.frame by the date, but I cannot perform the sum of the values, I am trying to use the function colSums.

Link of the database 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])
 1
Author: Alexandre Sanches, 2020-04-23

2 answers

Just enter 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 the column, you don't have to create an object (soma) for that.

 2
Author: neves, 2020-04-23 18:13:27

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 obitosaccumulated, you are putting as input a series (an object with a single dimension).

I managed to get to the result you seek by 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 to have helped to achieve the expected result, warns if it managed to solve. Any doubt calls again.

 2
Author: Felipe solares, 2020-04-23 18:28:30