Leonhardt Guass
Leonhardt Guass

Reputation: 793

Reshape a data frame that have multiple keys in column names from wide to long

I know that are already a lot of reshaping pages, but I did not find what I want and my problem is kind of unique.

I have the following dataset:

df <- data.frame(Year=rep(1:4,4),id=rep(1:4,each=4),key1equals1.key2equals1.key3equals1=1,key1equals2.key2equals1.key3equals1=2,key1equals1.key2equals2.key3equals2=3,key1equals2.key2equals1.key3equals2=4)

Essentially, there are five keys: Year, id, key1, key2, key3

The value of key1, key2, key3 are all included in the column names.

I want to following dataset:

Year id key1 key2 key3 value

If possible, I want to use base R.

Upvotes: 0

Views: 52

Answers (1)

zack
zack

Reputation: 5415

Drawing inspiration from Hadley's answer here:

library(tidyr)

df %>%
  gather(key, value, -Year, -id) %>%
  extract(key, c("key1", "key2", "key3"), 'key1equals([0-9])\\.key2equals([0-9])\\.key3equals([0-9])')

Upvotes: 1

Related Questions