Search code examples
rdataframestructure

Is there any way to rearrange this kind of data?


Each ID has a gender and age, and function data. I was wondering how I should get a data set in which I can analyze.

------------------------
original data form is:
ID gender age fun
1 M 10 2.5
1 M 10 2.4
1 M 10 3.3
1 M 10 5.5
1 M 10 2.2
2 F 11 4.4
2 F 11 3.3
2 F 11 2.2
2 F 11 1.1
2 F 11 3.3


I want a from of data like:
ID gender age fun
1 M 10 2.5 2.4 3.3 5.5 2.2
2 F 11 4.4 3.3 2.2 1.1 3.3

------------------------

Thank you in advance for your help.


Solution

  • A solution using tidyverse.

    library(tidyverse)
    
    dat2 <- dat %>%
      group_by(ID) %>%
      mutate(N = 1:n()) %>%
      spread(N, fun) %>%
      ungroup()
    dat2
    # # A tibble: 2 x 8
    #      ID gender   age   `1`   `2`   `3`   `4`   `5`
    #   <int> <chr>  <int> <dbl> <dbl> <dbl> <dbl> <dbl>
    # 1     1 M         10   2.5   2.4   3.3   5.5   2.2
    # 2     2 F         11   4.4   3.3   2.2   1.1   3.3
    

    DATA

    dat <- read.table(text = "ID gender age fun
    1 M 10 2.5
    1 M 10 2.4
    1 M 10 3.3
    1 M 10 5.5
    1 M 10 2.2
    2 F 11 4.4
    2 F 11 3.3
    2 F 11 2.2
    2 F 11 1.1
    2 F 11 3.3",
                      header = TRUE, stringsAsFactors = FALSE)