Reputation: 6784
I would like to convert that old piece of code to tidyverse. Can somebody help?
library(plyr)
ddply(dat,.(sex),function(x) tabulate(x[,1],nbins=5))
# result
# sex V1 V2 V3 V4 V5
#1 female 1 6 0 2 0
#2 male 2 11 3 0 0
dat <- structure(list(P1 = c(2, 2, 1, 2, 2, 2, 2, 1, 2, 4, 3, 2, 3,
2, 2, 2, 4, 2, 2, 1, 2, 3, 2, 2, 2), sex = structure(c(2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("female", "male"), class = "factor")), class = "data.frame", row.names = c(NA,
-25L))
Upvotes: 3
Views: 923
Reputation: 887541
In base R
, we can do with table
after converting the 'P1' column to factor
table(transform(dat, P1 = factor(P1, levels = 1:5,
labels = paste0("P1_", 1:5)))[2:1])
# P1
#sex P1_1 P1_2 P1_3 P1_4 P1_5
# female 1 6 0 2 0
# male 2 11 3 0 0
Or using dcast
from data.table
library(data.table)
dcast(setDT(dat), sex ~ factor(P1, levels = 1:5,
labels = paste0("P1_", 1:5)), drop = FALSE, length)
# sex P1_1 P1_2 P1_3 P1_4 P1_5
#1: female 1 6 0 2 0
#2: male 2 11 3 0 0
Upvotes: 1
Reputation: 16121
library(tidyverse)
# set number of bins
nb = 5
dat %>%
count(P1, sex) %>% # count combinations
complete(P1 = 1:nb, sex, fill = list(n = 0)) %>% # if a bin is missing add a zero count
spread(P1, n, sep = "_") # reshape dataset
# # A tibble: 2 x 6
# sex P1_1 P1_2 P1_3 P1_4 P1_5
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 female 1 6 0 2 0
# 2 male 2 11 3 0 0
Upvotes: 1