wide to long multiple columns issue

佐手、 提交于 2020-01-16 09:48:16

问题


I have something like this:

id    role1   Approved by Role1     role2          Approved by Role2
1      Amy        1/1/2019          David             4/4/2019
2      Bob        2/2/2019          Sara              5/5/2019
3      Adam       3/3/2019          Rachel            6/6/2019

I want something like this:

id    Name      Role        Approved     
1      Amy      role1       1/1/2019         
2      Bob      role1       2/2/2019        
3      Adam     role1       3/3/2019  
1      David    role2       4/4/2019         
2      Sara     role2       5/5/2019        
3      Rachel   role2       6/6/2019       

I thought something like this would work

 melt(df,id.vars= id,
  measure.vars= list(c("role1", "role2"),c("Approved by Role1", "Approved by Role2")),
  variable.name= c("Role","Approved"),
  value.name= c("Name","Date"))

but i am getting Error: measure variables not found in data:c("role1", "role2"),c("Approved by Role1", "Approved by Role2")

I have tried replacing this with the number of the columns as well and haven't had any luck.

Any suggestions?? Thanks!


回答1:


I really like the new tidyr::pivot_longer() function. It's still only available in the dev version of tidyr, but should be released shortly. First I'm going to clean up the column names slightly, so they have a consistent structure:

> df
# A tibble: 3 x 5
     id name_role1 approved_role1 name_role2 approved_role2
  <dbl> <chr>      <chr>          <chr>      <chr>         
1     1 Amy        1/1/2019       David      4/4/2019      
2     2 Bob        2/2/2019       Sara       5/5/2019      
3     3 Adam       3/3/2019       Rachel     6/6/2019  

Then it's easy to convert to long format with pivot_longer():

library(tidyr)

df %>%
    pivot_longer(
        -id,
        names_to = c(".value", "role"),
        names_sep = "_"
    )

Output:

     id role  name   approved
  <dbl> <chr> <chr>  <chr>   
1     1 role1 Amy    1/1/2019
2     1 role2 David  4/4/2019
3     2 role1 Bob    2/2/2019
4     2 role2 Sara   5/5/2019
5     3 role1 Adam   3/3/2019
6     3 role2 Rachel 6/6/2019


来源:https://stackoverflow.com/questions/57549204/wide-to-long-multiple-columns-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!