I have a simple data frame. The elements are individuals, the variables are activities, and the values are whether each individual has completed the activity.
df1 <- data.frame (student = c (1, 2, 3, 4, 5, 6),
budget= c("in progress", "not started", "completed", "not started", "not started", "in progress"),
resume = c ("not started", "completed", "completed", "not started", "completed", "in progress"),
cover = c("completed", "not started", "not started", "not started", "in progress", "in progress"))
I want to create a table where the rows are "completed," "in progress," and "not started," the columns are the activities ("budget," "resume," and "cover"), and the values are the count for each.
I have tried using the "group_by" function.
dt1 <- df1 %>%
group_by (budget, resume, cover) %>%
summarise(freq = n())
But this seems to be counting a combination of values.
What I want in the end is a table that looks like
df2 <- data.frame (progress = c("completed", "in progress", "not started"),
budget = c(1, 2, 3),
resume = c(3, 1, 2),
cover = c(1, 2, 3))
Any and all feedback is appreciated. Thank you.
In tidyverse
you may reshape the data to long format, count
and reshape to wide format.
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -student) %>%
count(name, value) %>%
pivot_wider(names_from = name, values_from = n)
However, I think it is easier in base R in this case -
sapply(df1[-1], table)
# budget resume cover
#completed 1 3 1
#in progress 2 1 2
#not started 3 2 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.