首页 > 解决方案 > 需要从 r 中的列中分离出变量名称

问题描述

所以我有一个非常糟糕的数据集,我不允许更改。我想采用“Draw_CashFlow”列并仅将某些值放入自己的列中。此外,我需要将变量全部设为一列(句号)(如果你愿意,可以宽到整洁)。

在下面的数据集中,我们有一列 (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 列中的变量名称将始终相同。

标签: rdataframedplyrtidyversetidyr

解决方案


这是一种假设以 an 开头的 Draw_CashFlow 值R是 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.

推荐阅读