Add factors from a data frame?

Asked

Viewed 1,479 times

1

I have the following df:

Factor  Valor
  F1     1.224
  F1     1.533
  F1     0,77429
  F2     3.477
  F2     2.6767
  F3     0.557
  F3     1

How do I get the total values?

2 answers

2

To have the sum of a variable relative to the value of another factor variable in a data frame, there are ways. My favorite is using the package dplyr:

First construct the following data frame with variable factor:

library(dplyr)
set.seed(32)
df <- data.frame(
                letras = as.factor(sample(size = 10000, replace = TRUE ,x = letters)),
                valor = rnorm(10000))

Thus, grouping the data with the function dplyr::group_by I can summarize the data with summarise:

> df %>% 
    +   dplyr::group_by(letras) %>% 
    +   dplyr::summarise(soma_valor = sum(valor))
# A tibble: 26 x 2
    letras soma_valor
    <fctr>      <dbl>
1      a -13.947423
2      b -37.894710
3      c  -4.600648
4      d  50.555644
5      e  30.048488
6      f  -3.667602
7      g -19.215489
8      h   2.892579
9      i  31.189657
10     j  17.085478
# ... with 16 more rows

To learn more about dplyr and all tidyverse, read this link here

1

Luiz, for a Data Frame you can use the ColSums() to get the values in the tables.

colSums(coluna[,-1])

or sum(dataFrame$Coluna)

and removing NA values sum(dataFrame$Coluna,na.rm=TRUE)

the [-1] ensures that the name of the column will not be counted.

Or for a more generic approach you can use

colSums(Filter(is.numeric, dataFrame$Coluna))

Note that you can get help on the console by typing ?sum or ?colSums

Source

Browser other questions tagged

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