首页 > 解决方案 > 我如何以编程方式选择要变异的列?

问题描述

示例数据:

Project  2016   2017   2018   2019
Proj1      42     36    400    250
Proj2      96    780     60    900
Proj3     180    230      0      0

我有一组今年的财务数据,还有前几年的财务数据。我正在尝试改变数据,以便将前三年添加到“以前的资金”列中。

数据具有标记为 2016、2017、2018、2019 等的列

Totals<-Totals %>% mutate("Previous Years"=`2016`+`2017`+`2018`)

现在,我实际上正在尝试设置它,以便我可以以编程方式选择它;明年,我宁愿看 2017 年、2018 年和 2019 年的数据,当然,我想设置它以便我可以输入年份数字,它会使用代码选择正确的列。

year = 2019

index<-which(colnames(Totals)==year)

Totals<-Totals%>%
##Here's where it gets hairy
mutate("Previous Years"=Totals[index-3]+Totals[index-2]+Totals[index-1])

Error: Column `Previous Years` is of unsupported class data.frame

所以,有一些问题。显然,我说错了,上面的场景 1 就像一个魅力,而第二个场景给出了一个错误。我觉得这与您通常用来在 dplyr 中调用具有不寻常名称的列的反引号有关。

做这样的事情的正确方法是什么?

标签: rdplyr

解决方案


我不认为你的数据是整洁的。如果你把它整理得井井有条,事情就会变得更容易。例如:

读入数据

library(dplyr)
library(tidyr)

Totals <- data.table::fread('Project  2016   2017   2018   2019
Proj1     $42    $36   $400   $250
Proj2     $96   $780    $60   $900
Proj3    $180   $230     $0     $0', header = TRUE)

year <- 2019

整理并计算以前的资金。

summ <- Totals %>% 
  gather(Year, Funding, -Project) %>% 
  mutate(Funding = readr::parse_number(Funding)) %>% 
  group_by(Project) %>% 
  summarise(Previous_funding = sum(Funding[Year %in% (year - 3):(year - 1)]))
# A tibble: 3 x 2
  Project Previous_funding
  <chr>              <dbl>
1 Proj1                478
2 Proj2                936
3 Proj3                410

您也可以使用mutate而不是summarise保留所有数据:

# A tibble: 12 x 4
# Groups:   Project [3]
   Project Year  Funding Previous_funding
   <chr>   <chr>   <dbl>            <dbl>
 1 Proj1   2016       42              478
 2 Proj2   2016       96              936
 3 Proj3   2016      180              410
 4 Proj1   2017       36              478
 5 Proj2   2017      780              936
 6 Proj3   2017      230              410
 7 Proj1   2018      400              478
 8 Proj2   2018       60              936
 9 Proj3   2018        0              410
10 Proj1   2019      250              478
11 Proj2   2019      900              936
12 Proj3   2019        0              410

或者,如果您愿意,您可以将之前的资金添加回原来的宽表中:

left_join(Totals, summ, 'Project')
 Project 2016 2017 2018 2019 Previous_funding
1   Proj1  $42  $36 $400 $250              478
2   Proj2  $96 $780  $60 $900              936
3   Proj3 $180 $230   $0   $0              410

推荐阅读