Adding factors to a data frame?

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?

    
asked by anonymous 26.06.2017 / 20:52

2 answers

1

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

colSums(coluna[,-1])

or sum(dataFrame$Coluna)

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

[-1] ensures that the column name is not 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

Font

    
26.06.2017 / 21:17
1

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

First I build the following data frame with factor variables:

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

So, grouping the data with the dplyr::group_by function 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 the whole tidyverse, read this link here

    
26.06.2017 / 21:20