'mean or median in table in R (like pivot in excel)
I try to get out of my data a table and I don't know how to do this. This is my data. The header is in German. Because of this is my r-code in german too. sorry for that but I hope someone can help me with the subject .
I would like to get this output as a pivot table in r. I tryed to translate in english:
In r i tried different ways to get to a solution (library(pivottabler):
This on worked a bit, but I couldn't calculate the median. counting the rows
version with testing median calculation
Here I don' get the value into the table table without values
I also tried this. But this is not the output I am looking for. group_by and summarise
Thanks for your help. mg
Solution 1:[1]
It would be easier to give you a more applicable answer if you gave us a more reproducible example.
However, what I think you want is easily accomplished with functions from the dplyr package. This answer uses the built-in iris dataset. It groups by the categorical variable Species and calculates the median by Species for all numeric columns in the data frame.
library(dplyr)
iris %>%
group_by(Species) %>%
summarise(across(where(is.numeric), median))
# A tibble: 3 x 5
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 5 3.4 1.5 0.2
2 versicolor 5.9 2.8 4.35 1.3
3 virginica 6.5 3 5.55 2
To calculate the mean over all numeric columns, use mean where the above code has median.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben Norris |
