Casperge
Casperge

Reputation: 3

How to partially transpose a dataframe in R? (specific column to row)

I would like to change a specific column into a row where the value of each cell is based on another column.

My dataframe looks like the following:

Race State Region Decile Freq
African a A 1 3
Caucasian a A 1 7
Asian a A 1 9
Mulatto a A 1 5
African b B 1 12
Caucasian b B 1 2
Asian b B 1 8
Mulatto b B 1 5

I want to change the column Race into a row (where Freq determines the value of each cell), so I get the following output:

State Region Decile African Caucasian Asian Mulatto
a A 1 3 7 9 5
b B 1 12 2 8 5

The ultimate aim here is to compute the relative frequency of each Race per State, Region and Decile but that is for another day

Upvotes: 0

Views: 139

Answers (1)

Waldi
Waldi

Reputation: 41220

With tidyr::pivot_wider:

library(tidyr)

data %>% pivot_wider(names_from = 'Race', values_from = Freq)
# A tibble: 2 x 7
  State Region Decile African Caucasian Asian Mulatto
  <chr> <chr>   <int>   <int>     <int> <int>   <int>
1 a     A           1       3         7     9       5
2 b     B           1      12         2     8       5

Data:

data <- read.table(text=
'Race   State   Region  Decile  Freq
African     a   A   1   3
Caucasian   a   A   1   7
Asian   a   A   1   9
Mulatto     a   A   1   5
African     b   B   1   12
Caucasian   b   B   1   2
Asian   b   B   1   8
Mulatto     b   B   1   5', header=T)

Upvotes: 1

Related Questions