在 R 中使用 Dcast 转换数据帧

Using Dcast in R to transform dataframe

我有以下数据框。并希望得到想要的输出

data.frame(df)
num  Name1   Result1 Name2  Result2   Name3  Result3
1    75%      74      100%    101      50%   50
2    75%      73      100%    101      50%   49
3    50%      50      100%    105      125%  128

我使用以下方法尝试了 Dcast reshape2::dcast(df, num ~ Name1 + Name2 + Name3, value.var=c("Result1", "Result2", "Result3"))

Dcast 的输出接近我想要的输出,但我只想要唯一的 'Name' 值作为我的新列。我可以想象我可以在使用 Dcast 之前使用聚合清理 table 但这似乎过分了?不知道有没有更快的方法?

期望的输出:

num  50%   75%      100%    125%    
1    50    74       101     NA    
2    49    73       101     NA      
3    50    NA       100     128 

如有任何帮助,我将不胜感激

您可以找到有关步骤 and here 的更多信息。

dat %>% 
  rename_at(vars(matches("[0-9]")),
            ~str_replace(.,"(\d)(\w*)","\2_\1")) %>% 
  pivot_longer(cols=matches("_"),names_to=c(".value","group"),
               names_sep="_") %>% 
  dplyr::select(-group) %>% 
  pivot_wider(names_from = "Name",values_from="Result")

# A tibble: 3 x 5
    num `75%` `100%` `50%` `125%`
  <int> <int>  <int> <int>  <int>
1     1    74    101    50     NA
2     2    73    101    49     NA
3     3    NA    105    50    128

或者...

reshape(dat, idvar="num", direction="long", 
        varying=list(Name=c(2,4,6), Result=c(3,5,7)),
        v.names = c("Name", "Result") ) %>% 
  dplyr::select(-time) %>% 
  dcast(num ~ Name)
    
  num 50% 75% 100% 125%
1   1  50  74  101   NA
2   2  49  73  101   NA
3   3  50  NA  105  128 

以长格式获取数据,因此我们在 NameResult 两列中有数据。然后我们可以得到宽格式的数据。

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -num, 
               names_to = '.value', 
               names_pattern = '([A-Za-z]+)\d+') %>%
  arrange(readr::parse_number(Name)) %>%
  pivot_wider(names_from = Name, values_from = Result)

#   num   `50%` `75%` `100%` `125%`
#  <int> <int> <int>  <int>  <int>
#1     1    50    74    101     NA
#2     2    49    73    101     NA
#3     3    50    NA    105    128