如何在R中使用相似的列名将数据从宽格式转换为长格式?

时间:2018-08-24 09:58:14

标签: r dataframe

最近,我从一个网站上抓取了数据,它类似于下面function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false let proto = obj while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(obj) === proto } let obj = { a: { b: 'sss', c: ['ss', 'sss'] } } console.log(isPlainObject(obj));变量中的数据表。

input

我要input <- data.frame( "Date" = sprintf("%02d-Jan", 1:15), "Type_event_1" = c(rep("Skiing", 3), rep("Marathon", 7), rep("Skating", 5)), "sport_event_1"= c(rep("Alpine skiing",4), rep("Biathlon",6), rep("Curling",3), rep("Figure skating",2)), "Type_event_2" = c(rep("Skiing", 4), rep("Marathon", 6),rep("Ice-Hockey", 3), rep("Skating", 2)), "sport_event_2"= c(rep("Skeleton",4), rep("Luge",6), rep("Hockey",3), rep("Ski Jumping",2)) ) 带有共同后缀(“ event_1”,“ event_2”)的列与“日期”列一一排在后面。在这种情况下,我只有4列,即2个事件,如果我有40列,即_ 20个这样的事件该怎么办。 如何使用for循环执行此操作?
    预期的输出如下所示:

rbind

2 个答案:

答案 0 :(得分:3)

尝试

library(data.table)
library(dplyr)
out1=data.table::melt(input[c(1,grep("Type_event_",names(input)))],"Date")[,c(1,3)]
out2=data.table::melt(input[c(1,grep("sport_event_",names(input)))],"Date")[,c(1,3)]
final<-cbind(out1,out2[,-1])
names(final)<-c("Date","Type_event","sport_event")

答案 1 :(得分:1)

library(tidyverse)

tbl_df(input) %>%
  unite(v1, Type_event_1, sport_event_1) %>%
  unite(v2, Type_event_2, sport_event_2) %>%
  gather(v1,v2, -Date) %>%
  separate(v2, c("Type_event","sport_event"), sep = "_") %>%
  select(-v1)

# # A tibble: 30 x 3
#     Date   Type_event sport_event  
#    <fct>  <chr>      <chr>        
# 1 01-Jan Skiing     Alpine skiing
# 2 02-Jan Skiing     Alpine skiing
# 3 03-Jan Skiing     Alpine skiing
# 4 04-Jan Marathon   Alpine skiing
# 5 05-Jan Marathon   Biathlon     
# 6 06-Jan Marathon   Biathlon     
# 7 07-Jan Marathon   Biathlon     
# 8 08-Jan Marathon   Biathlon     
# 9 09-Jan Marathon   Biathlon     
#10 10-Jan Marathon   Biathlon     
# # ... with 20 more rows

注意:我仅将tbl_df(input)用于可视化目的。您只能使用input %>% ...