需要从r中的列中分离出变量名

时间:2019-07-03 18:34:27

标签: r dataframe dplyr tidyverse tidyr

所以我的数据集非常糟糕,不允许更改。我想选择“ Draw_CashFlow”列,并在其自己的列中仅添加某些值。另外,我需要将变量全部设置为一列(句号)(如果可以的话,应整整排成Tidy)。

在下面的数据集中,我们有一列(Draw_CashFlow),该列以所讨论的变量开头,后跟ID列表,然后对下一个变量重复。有些变量可能具有NA条目。

structure(list(Draw_CashFlow = c("Principal", "R01", 
"R02", "R03", "Workout Recovery Principal", 
"Prepaid Principal", "R01", "R02", "R03", 
"Interest", "R01", "R02"), `PERIOD 1` = c(NA, 
834659.51, 85800.18, 27540.31, NA, NA, 366627.74, 0, 0, NA, 317521.73, 
29175.1), `PERIOD 2` = c(NA, 834659.51, 85800.18, 27540.31, NA, 
NA, 306125.98, 0, 0, NA, 302810.49, 28067.8), `PERIOD 3` = c(NA, 
834659.51, 85800.18, 27540.31, NA, NA, 269970.12, 0, 0, NA, 298529.92, 
27901.36), `PERIOD 4` = c(NA, 834659.51, 85800.18, 27540.31, 
NA, NA, 307049.06, 0, 0, NA, 293821.89, 27724.4)), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"))

现在它是所需变量的有限列表(委托人,锻炼恢复委托人,预付委托人和利息),因此我尝试制作一个循环,在该循环中查看其是否存在然后收集,但这是不正确的。

将变量与Draw_CashFlow分开设置后,我希望它看起来像这样(前四行,忽略变量缩写)。

ID  Period   Principal  Wrk_Reco_Principal   Prepaid_Principal    Interest
R01      1   834659.51                  NA           366627.74   317521.73
R02      1    85800.18                  NA                0.00    29175.10
R03      1    27540.31                  NA                0.00          NA
R01      2   834659.51                  NA           306125.98   302810.49 

注意:Wrl_Reco_Principal是NA,因为此Draw_CashFlow中没有此变量的ID。请记住,它应该可以抵抗任何数量的ID,但是Draw_CashFlow列中的变量名将始终相同。

1 个答案:

答案 0 :(得分:1)

这是一种假设以R开头的Draw_CashFlow值是ID号的方法。如果这种方法无法解决问题,则可能需要其他方法(例如!Draw_CashFlow %in% LIST_OF_VARIABLES)。

df %>%
  # create separate columns for ID and Variable
  mutate(ID = if_else(Draw_CashFlow %>% str_starts("R"),
                      Draw_CashFlow, NA_character_),
         Variable = if_else(!Draw_CashFlow %>% str_starts("R"),
                        Draw_CashFlow, NA_character_)) %>%
  fill(Variable) %>%  # Fill down Variable in NA rows from above
  select(-Draw_CashFlow) %>%
  gather(Period, value, -c(ID, Variable)) %>%  # Gather into long form
  drop_na() %>%
  spread(Variable, value, fill = 0) %>% # Spread based on Variable
  mutate(Period = parse_number(Period))


# A tibble: 12 x 5
   ID    Period Interest `Prepaid Principal` Principal
   <chr>  <dbl>    <dbl>               <dbl>     <dbl>
 1 R01        1  317522.             366628.   834660.
 2 R01        2  302810.             306126.   834660.
 3 R01        3  298530.             269970.   834660.
 4 R01        4  293822.             307049.   834660.
 5 R02        1   29175.                  0     85800.
 6 R02        2   28068.                  0     85800.
 7 R02        3   27901.                  0     85800.
 8 R02        4   27724.                  0     85800.
 9 R03        1       0                   0     27540.
10 R03        2       0                   0     27540.
11 R03        3       0                   0     27540.
12 R03        4       0                   0     27540.