0

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.

Leonhardt Guass
  • 603
  • 5
  • 19

1 Answers1

1

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])')
zack
  • 4,570
  • 1
  • 17
  • 25