I am new to R. So far I have managed to find solutions for my problems and adapt my code. However, I have not been able to solve the following problem for 2 days. Probably, there is a very easy solution, but my skills are too limited. Sorry in advance (also for my English).
I try to order numerical values from one column only in accordance to specific value ranges. The ultimate goal is to have a table in a Rmarkdown file, which list the summations of those values in their representative ranges.
So far, I have only managed to create a tibble with a summation column. Unfortunately, I stuck there. I can not transfer/keep the summation column, even when I transformed the int- into a dbl-column. Knitting the file still only shows the labels (Level 1, Level 2, ...) in a non-summarized fashion. This also happens when I try to print it. The summations would disappear.
tl;dr: How can I keep this summation column, in order to use it in a table in Rmarkdown?
Thanks for any advice!
library(tidyverse)
library(knitr)
a <- c(12.3, 13.8, 14.5, 15.4, 16.5, 12.7, 14.2, 16.1, 13.9, 18)
a
## [1] 12.3 13.8 14.5 15.4 16.5 12.7 14.2 16.1 13.9 18.0
b <- cut(a, c(-Inf, '12', '13', '14', '15', '16', '17', Inf), labels=c('Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5', 'Level 6', 'Level 7'))
table(b)
## b
## Level 1 Level 2 Level 3 Level 4 Level 5 Level 6 Level 7
## 0 2 2 2 1 2 1
class(b)
## [1] "factor"
b <- as.data.frame(b)
b %>%
group_by(b, .drop = FALSE) %>%
dplyr::summarise(Numbers = n()) %>%
mutate(Numbers = rowSums(.[-1]))
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 7 x 2
## b Numbers
## <fct> <dbl>
## 1 Level 1 0
## 2 Level 2 2
## 3 Level 3 2
## 4 Level 4 2
## 5 Level 5 1
## 6 Level 6 2
## 7 Level 7 1
class(b)
## [1] "data.frame"
print(as_tibble(b))
## # A tibble: 10 x 1
## b
## <fct>
## 1 Level 2
## 2 Level 3
## 3 Level 4
## 4 Level 5
## 5 Level 6
## 6 Level 2
## 7 Level 4
## 8 Level 6
## 9 Level 3
## 10 Level 7
kable(b)
b
Level 2
Level 3
Level 4
Level 5
Level 6
Level 2
Level 4
Level 6
Level 3
Level 7
You just forgot to save your updated b object :)
b <- as.data.frame(b)
b <- b %>%
group_by(b, .drop = FALSE) %>%
dplyr::summarise(Numbers = n()) %>%
mutate(Numbers = rowSums(.[-1]))
Or you could just pipe from the first line like so:
b <- as.data.frame(b) %>%
group_by(b, .drop = FALSE) %>%
dplyr::summarise(Numbers = n()) %>%
mutate(Numbers = rowSums(.[-1]))