重组数据框 R - 在一列中收集年份

问题描述

我有一个看起来像这样的大数据框:

位置 type 2005 2006 2007
判刑 女性 大学 判刑 女性 大学 判刑 女性 大学
巴黎 1
巴黎 2
巴黎 3
马德里 1
马德里 2
迈阿密 1

我想重组它,看起来像这样:

位置 输入 判刑 女性 大学
2005 巴黎 1
2005 巴黎 2
2005 巴黎 3
2005 马德里 1
2005 马德里 2
2005 迈阿密 1
2006 巴黎 1
2006 巴黎 2
2006 巴黎 3
2006 马德里 1
2006 马德里 2
2006 迈阿密 3

请不要关注两个表的内部有效性。这只是为了可视化。

我在 R 中尝试了 Gather 函数,但失败了,因为它似乎每年只需要一个变量而不是三个(在我的例子中:被判刑、女性、大学)。

有什么建议吗?

谢谢

解决方法

我尝试复制您的示例:

test <- structure(list(location = c(NA,"Paris","Madrid","Miami"),type = c(NA,1,2,3,1),`2005...3` = c("Sentenced","Yes","No","Yes"),`2005...4` = c("Female","No"),`2005...5` = c("College",`2006...6` = c("Sentenced",`2006...7` = c("Female",`2006...8` = c("College",`2007...9` = c("Sentenced",`2007...10` = c("Female",`2007...11` = c("College","Yes")),row.names = c(NA,-7L
 ),class = c("tbl_df","tbl","data.frame"))

您基本上需要合并前两行以形成标题并使用以下代码

names(test) <- paste(names(test),test[1,],sep = "_") 
test <- test[-1,]

test <- gather(test,"key","value",3:11)
test <- test %>% separate(key,c("Year","Key"),"_")      
test <- test %>% separate(Year,"Garbage"),"[.]")
test <- test %>% select(-Garbage)
test <- test %>% spread(Key,value)