-1

I have a data frame sex(male & female), age(child & adult), survive(yes & no) and frequency. How can I create a cross tab of sex and age?

sex     age    survive   freq
male    child   yes      4
male    adult   yes      0
female  child   yes      6
female  adult   yes      3
male    child   no       1
male    adult   no       0
female  child   no       2
female  adult   no       1
dc37
  • 15,840
  • 4
  • 15
  • 32
Zaliro
  • 1

1 Answers1

1

I think you are looking for reshaping your data using pivot_wider from tidyr:

library(tidyr)
df %>% pivot_wider(., names_from = age, values_from = freq)

# A tibble: 4 x 4
  sex    survive child adult
  <fct>  <fct>   <int> <int>
1 male   yes         4     0
2 female yes         6     3
3 male   no          1     0
4 female no          2     1

or

library(tidyr)
df %>% pivot_wider(., names_from = c(age, survive), values_from = freq)

# A tibble: 2 x 5
  sex    child_yes adult_yes child_no adult_no
  <fct>      <int>     <int>    <int>    <int>
1 male           4         0        1        0
2 female         6         3        2        1

Is it what you are looking for ? If not, can you provide the expected outcome ?

Data

df = structure(list(sex = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 
1L), .Label = c("female", "male"), class = "factor"), age = structure(c(2L, 
1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("adult", "child"), class = "factor"), 
    survive = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("no", 
    "yes"), class = "factor"), freq = c(4L, 0L, 6L, 3L, 1L, 0L, 
    2L, 1L)), class = "data.frame", row.names = c(NA, -8L))
dc37
  • 15,840
  • 4
  • 15
  • 32
  • Simple: I want to do a Chi-Square test between Class and Sex using Titanic data from R package titanic. {install.packages("titanic")}. Please assist – Zaliro Dec 30 '19 at 14:30