Reputation: 119
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 -
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
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)
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
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