Geo7212
Geo7212

Reputation: 81

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

Upvotes: 2

Views: 590

Answers (2)

www
www

Reputation: 39154

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)

Upvotes: 1

r_alanb
r_alanb

Reputation: 913

Using tidyr is one option.

tidyr::pivot_longer() converts crop_land and fishing_ground to variable-value pairs. tidyr::unite() combines the record and variable to new names. tidyr::pivot_wider() creates the wide data frame you are after.

library(tidyr)
library(magrittr) # for %>%

tst <-  data.frame(
  record = c("BiocapPerCap", "Consumption"), 
  crop_land = c(1.5, 2.3), 
  fishing_ground = c(3.4, 0.5)
)

pivot_longer(tst, -record) %>% 
  unite(new_name, record, name, sep = '.') %>% 
  pivot_wider(names_from = new_name, values_from = value)

Upvotes: 0

Related Questions