Rspacer
Rspacer

Reputation: 2429

Convert from long to wide format with multiple unique variables to other unique variables in R

I am trying to convert from long to wide format but multiple columns denote the unique rows. In the example below, the block, density, species columns denote the unique individuals. Every individual has 2 or 3 rows associated with area and size. I want to convert the area and size to wide format.

This is my dataset

block <- c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2)
species <- c("A","A","A","A","B","B","B","B","A","A","A","A","B","B","B","B","B")
den <- c("20","20","50","50","20","20","50","50","20","20","50","50","20","20","50","50","50")


block <- as.factor(block)
den <- as.factor(den)
species <- as.factor(species)

area <- c(1:17)
size <- c(17:33)

df <- data.frame(block, species, den, area, size)

I want to final dataset with only the unique individuals

  block   species   den   area.1  area.2  area.3  size.1  size.2  size.3
    1        A       20     1       2       NA      17      18      NA
    1        A       50     3       4       NA      19      20      NA
    .....
    2        B       50     15      16      17      31      32      33

Note: Other answers that I have persued do not use multiple columns to denote the uniquness of the rows

Upvotes: 1

Views: 451

Answers (1)

akrun
akrun

Reputation: 887901

We can use pivot_wider after creating a sequence column by group

library(dplyr)
library(tidyr)
df %>% 
    group_by(block, species, den) %>% 
    mutate(rn = row_number()) %>% 
    ungroup %>% 
    pivot_wider(names_from = rn, values_from = c(area, size), names_sep = ".")
# A tibble: 8 x 9
#  block species den   area.1 area.2 area.3 size.1 size.2 size.3
#  <fct> <fct>   <fct>  <int>  <int>  <int>  <int>  <int>  <int>
#1 1     A       20         1      2     NA     17     18     NA
#2 1     A       50         3      4     NA     19     20     NA
#3 1     B       20         5      6     NA     21     22     NA
#4 1     B       50         7      8     NA     23     24     NA
#5 2     A       20         9     10     NA     25     26     NA
#6 2     A       50        11     12     NA     27     28     NA
#7 2     B       20        13     14     NA     29     30     NA
#8 2     B       50        15     16     17     31     32     33

Upvotes: 2

Related Questions