处理大量数据 manipulation/cleaning 时,如何最好地在 R 中构建我的代码?

How best to structure my code in R when doing a lot of data manipulation/cleaning?

作为初学者,我有一个关于最有效编码的一般性问题 - 我有一个非常广泛的数据集 (374 obs),我必须对其进行一些操作。我将主要使用 'mutate' 和 'unite' 。我的问题是:

我现在编写代码的方式是,每次我做一些新的事情(即,如果我将 6 列合并为一列),然后我会为此编写一个单独的代码并创建一个新的数据框。

下面还有 'mutate' 的另一个代码,就像我必须通过对两列求和来创建一个新变量一样。

这里有一个例子:

#1B. Combine location columns. 
combinedlocations <- rawdata1 %>% unite(location, locations1,locations2, locations3, na.rm = TRUE, 
remove=TRUE)
combinedlocations <- combinedlocations[-c(6:7)] #drop the unwanted columns

#2. Combine Sector together into one new column: Sector
#B. Combine columns, but override if Type.of.org = 'Independent Artist', where Sector = "Independent 
Artist"
Combinedsectors <- combinedlocations %>% unite(Sector, Sectors, na.rm=TRUE, remove=TRUE)  %>% 

我基本上为每个操作创建一个新的数据框,使用我刚创建的数据框。

这是正确的吗?这就是我在 SAS 上学会做这件事的方式。或者,是否最好在一个数据帧(可能是 rawdata2)中完成所有操作?有没有办法使用 %>% 将所有这些代码组合在一起? (我仍在努力学习管道的工作原理)

这是在“基于意见”的边缘,但这是一个很好的问题。 tl;dr这不是很重要,主要是你喜欢的风格。

  • 将所有内容放在一个长管道序列 (a %>% b %>% c %>% d) 中,没有中间分配意味着您没有那么多的中间对象使您的工作区变得混乱;这意味着 (1) 你不必为它们全部想出名字 (data1, data2, ...) 并且 (2) 你不会耗尽内存来做很多额外的事情对象(除非您使用大数据,否则这不是问题)

另一方面,

  • 将所有内容放在一个长管道序列中会使调试变得更加困难,因为如果出现问题,将更难检查中间结果; this blog post 列出了多种 packages/tools 方便调试管道序列。

我倾向于使用大约 5-6 行的管道序列。您的管道格式代码看起来像这样...

#1B. Combine location columns. 
Combinedsectors <- (rawdata1 
   %>% unite(location, locations1,locations2, locations3, 
             na.rm = TRUE, remove=TRUE)
   %>% select(-(6:7)) 
#2. Combine Sector together into one new column: Sector
#B. Combine columns, but override if Type.of.org = 'Independent Artist', where Sector = "Independent Artist"
   %>% unite(Sector, Sectors, na.rm=TRUE, remove=TRUE)  
   %>%  ... <whatever>
)