Shakil Ahmed Shaon
Shakil Ahmed Shaon

Reputation: 119

How to combine multiple dichotomous variable (yes/no) and get multiple response table in R?

In my dataset,and I have several variables like this -

Hypertension = 1,0,1,1,1,1,0,1
Diabetes = 1,1,0,0,1,1,0,1
Other NCD = 1,1,0,0,0,0,1,1

here, 1 = yes and 0 = No

Now I want to bind all of these "yes" responses from the above variables and create a multiple responses table like this -

enter image description here

SPSS has a function called "Multiple Response". This image is one of the outputs of this function. How do I create this table?

Thanks in advance.

Upvotes: 0

Views: 969

Answers (2)

akrun
akrun

Reputation: 887048

With base R, we can do

dat1 <- transform(stack(colSums(dat)), n = nrow(dat))
dat1$percent <- 100 *dat1$values/dat1$n
dat1$overall <- round(100 * dat1$values/sum(dat1$n), 2)

data

dat <- data.frame(
  Hypertension = c(1,0,1,1,1,1,0,1),
  Diabetes =  c(1,1,0,0,1,1,0,1),
  `Other NCD` = c(1,1,0,0,0,0,1,1),
  check.names = FALSE
)

Upvotes: 1

r2evans
r2evans

Reputation: 160417

Please try this.

dat <- data.frame(
  Hypertension = c(1,0,1,1,1,1,0,1),
  Diabetes =  c(1,1,0,0,1,1,0,1),
  `Other NCD` = c(1,1,0,0,0,0,1,1),
  check.names = FALSE
)

library(dplyr)
library(tidyr) # pivot_longer
dat %>%
  tidyr::pivot_longer(everything(), names_to="k", values_to="v") %>%
  group_by(k) %>%
  summarize(
    n = n(), 
    cases = sum(v), 
    percent = 100 * cases / n()
  ) %>%
  ungroup() %>%
  mutate(overall = 100 * cases / sum(n))
# # A tibble: 3 x 5
#   k                n cases percent overall
#   <chr>        <int> <dbl>   <dbl>   <dbl>
# 1 Diabetes         8     5    62.5    20.8
# 2 Hypertension     8     6    75      25  
# 3 Other NCD        8     4    50      16.7

Upvotes: 2

Related Questions