Search code examples
rdataframecalculated-columns

How to create a column for each level of another column in R?


The goal I am trying to achieve is an expanded data frame in which I will have created a new column for each level of a specific column in R. Here is a sample of the initial data frame and the data frame I am trying to achieve:

Original Data Frame:

record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5

Goal Data Frame:

crop_land.BiocapPerCap     crop_land.Consumption     fishing_ground.BiocapPerCap      fishing_ground.Consumption
1.5                        2.3                       3.4                              0.5

Solution

  • We can use pivot_wider from the tidyr package as follows.

    library(tidyr)
    library(magrittr)
    
    dat2 <- dat %>%
      pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"),
                  names_sep = ".")
    dat2
    # # A tibble: 1 x 4
    #   crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPer~ fishing_ground.Consumpti~
    #                    <dbl>                 <dbl>                     <dbl>                     <dbl>
    # 1                    1.5                   2.3                       3.4                       0.5
    

    DATA

    dat <- read.table(text = "record           crop_land     fishing_ground
    BiocapPerCap     1.5           3.4
    Consumption      2.3           0.5",
                      header = TRUE, stringsAsFactors = FALSE)