Search code examples
rtidyrspread

tidyr::spread resulting in multiple rows


I have a similar problem than the following, but the solution presented in the following link does not work for me: tidyr spread does not aggregate data

I have a df in the following structure:

    UndesiredIndex  DesiredIndex    DesiredRows Result
1   x1A x1  A   50,32
2   x1B x2  B   7,34
3   x2A x1  A   50,33
4   x2B x2  B   7,35

Using the code below:

  dftest <- bd_teste %>%
  select(-UndesiredIndex) %>%
  spread(DesiredIndex, Result)

I expected the following result:

DesiredIndex    A   B
A   50,32   50,33
B   7,34    7,35

Although, I keep getting the following result:

    DesiredIndex    x1  x2
1   A   50.32   NA
2   B   7.34    NA
3   A   NA  50.33
4   B   NA  7.35

PS: Sometimes I force the column UndesiredIndex out with select(-UndesiredIndex), but I keep getting the following message:

Adding missing grouping variables: UndesiredIndex

Might be something easy to stack those rows, but I'm new to R and have been trying so hard to solve this but without success. Thanks in advance!


Solution

  • We group by DesiredIndex, create a sequence column and then do the spread:

    library(tidyverse)
    
    df1 %>% 
        select(-UndesiredIndex) %>% 
        group_by(DesiredIndex) %>% 
        mutate(new = LETTERS[row_number()]) %>% 
        ungroup %>%
        select(-DesiredIndex) %>% 
        spread(new, Result)
    
    # A tibble: 2 x 3
    #  DesiredRows A     B    
    #  <chr>       <chr> <chr>
    #1 A           50,32 50,33
    #2 B           7,34  7,35 
    

    Data

    df1 <- structure(
        list(
            UndesiredIndex = c("x1A", "x1B", "x2A", "x2B"), 
            DesiredIndex = c("x1", "x2", "x1", "x2"), 
            DesiredRows = c("A", "B", "A", "B"), 
            Result = c("50,32", "7,34", "50,33", "7,35")
        ), 
        class = "data.frame", 
        row.names = c("1", "2", "3", "4")
    )