透视R Statfile的多个列

问题描述 投票:1回答:1

我有一个R数据帧,有120,000行和34列。我希望对这些列中的3个进行透视,但保留该数据帧中的所有其他列。

以下面的记录(虚构)为例,遗憾的是我无法粘贴图像或Excel工作簿。

Initial  Initial Code  Renewal Renewal Code Other Other Code  Date    Consultant 
400      52070/1       200     52080/2      250   52090/1     1-1-18  Bill

有没有办法可以转动3个代码列,即初始代码,续订代码,其他代码,但仍然包括所有剩余的列。基本上它会如下所示:

Initial Code      Renewal Other Date    Consultant
400     52070/1   200     250   1-1-18  Bill
400     52080/1   200     250   1-1-18  Bill
400     52090/1   200     250   1-1-18  Bill

或者更好的是:

Amount Code      Date     Consultant  Type
400    52070/1   1-1-18   Bill        Initial
200    52080/1   1-1-18   Bill        Renewal
250    52090/1   1-1-18   Bill        Other

我很欣赏底部基本上是两层转换,第一个建议并不完美,但对我来说这将是一个可行的布局。

不幸的是,我不能在这里使用Excel作为解决方法。

非常感谢任何可能提出的帮助,Eoghan

r pivot-table
1个回答
0
投票

你能尝试这样的东西吗?

df %>%
  select(-grep("Code", names(df))) %>%
  gather(Type, Amount, -Date, -Consultant) %>%
  inner_join(df %>%
              select(-Initial, -Renewal, -Other) %>%
              gather(Type, Code, -Date, -Consultant) %>%
              mutate(Type=gsub(".Code","",Type)))

输出是:

    Date Consultant    Type Amount    Code
1 1-1-18       Bill Initial    400 52070/1
2 1-1-18       Bill Renewal    200 52080/2
3 1-1-18       Bill   Other    250 52090/1

#sample data
df <- structure(list(Initial = 400L, Initial.Code = "52070/1", Renewal = 200L, 
    Renewal.Code = "52080/2", Other = 250L, Other.Code = "52090/1", 
    Date = "1-1-18", Consultant = "Bill"), .Names = c("Initial", 
"Initial.Code", "Renewal", "Renewal.Code", "Other", "Other.Code", 
"Date", "Consultant"), class = "data.frame", row.names = c(NA, 
-1L))
© www.soinside.com 2019 - 2024. All rights reserved.