Creating a table with R

2.5k views Asked by At

Example 10.1. Let the blood types and gender of 40 persons are as follows:
(O,Male),(O,Female),(A,Female),(B,Male),(A,Female),(O,Female),(A,Male), (A,Male),(A,Female),(O,Male),(B,Male),(O,Male),B,Female),(O,Male),(O,Male), (A,Female),(O,Male),(O,Male),(A,Female),(A,Female),(A,Male),(A,Male), (AB,Female),(A,Female),(B,Female),(A,Male),(A,Female),(O,Male),(O,Male), (A,Female),(O,Male),(O,Female),(A,Female),(A,Male),(A,Male),(O,Male), (A,Male),(O,Female),(O,Female),(AB,Male).
Summarizing data in a two-way frequency table by using SPSS:

Can I use R to do so?

2

There are 2 answers

0
Rui Barradas On

You should post your data in a more useable form. Such as posting the output of dput(x), where x is the name of your dataset. Most of the work was to get what you've posted in a data.frame.

x <- "(O,Male),(O,Female),(A,Female),(B,Male),(A,Female),(O,Female),(A,Male),
      (A,Male),(A,Female),(O,Male),(B,Male),(O,Male),B,Female),(O,Male),
      (O,Male), (A,Female),(O,Male),(O,Male),(A,Female),(A,Female),(A,Male),
      (A,Male), (AB,Female),(A,Female),(B,Female),(A,Male),(A,Female),
      (O,Male),(O,Male), (A,Female),(O,Male),(O,Female),(A,Female),(A,Male),
      (A,Male),(O,Male), (A,Male),(O,Female),(O,Female),(AB,Male)"

s <- sub("\\(", "", strsplit(x, "\\),")[[1]])
s <- sub("\\)", "", s)
s <- strsplit(s, ",")
s <- lapply(s, trimws)
dat <- as.data.frame(do.call(rbind, s))
names(dat) <- c("BloodType", "Sex")

In base R there are functions to create two-way tables.

xtabs(~ BloodType + Sex, data = dat)
#         Sex
#BloodType Female Male
#       A      10    8
#       AB      1    1
#       B       2    2
#       O       5   11
1
Edu On

Look at the example below using dplyrand janitor

id = rep(1:40)
gender = sample(c("M", "F"), 40, TRUE)
blood = sample(c("O", "A"), 40, TRUE)

df = data.frame(id, gender, blood)

library(dplyr)

> df %>% group_by(gender, blood) %>% tally()
# A tibble: 4 x 3
# Groups:   gender [?]
  gender  blood     n
  <fctr> <fctr> <int>
1      F      A    11
2      F      O     8
3      M      A     8
4      M      O    13

library(janitor)

df %>% tabyl(gender, blood)

gender  A  O
1      F 11  8
2      M  8 13