r - 需要从 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 列中的变量名称将始终相同。
解决方案
这是一种假设以 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.
推荐阅读
- python - 从满足条件的集合中返回任意元素
- python - Python:无法将字符串转换为浮点数:
- angular - Angular parameterized route change parameter but maintain the rest of the route
- matlab - Matlab中的卡方独立性
- c - C GTK - 尝试获取 TreeView 中最后一项的索引号时的 SIGSEGV
- python - Locale Norway/Sweden chcp 65001" and "chcp 1252 CSV File not Formatted correctly
- reactjs - React: Cannot update a component from inside the function body of a different component
- ruby - 红宝石中的内存泄漏
- c# - Serilog:防止创建空日志文件
- python - Qt for Python:使用 python 创建封装的 qml 模块