如何避免复杂的for循环?

时间:2019-01-31 08:55:18

标签: r for-loop

我目前正在处理一系列大型数据集,并且我试图改善在R中编写脚本的方式。我倾向于主要利用for循环,因为我知道这可能是麻烦且缓慢的,尤其是对于非常大的数据集

我听说很多人推荐apply()系列以避免复杂的for循环,但是我一直在努力使用它们一次性应用多个功能。

以下是一些简单的示例数据:

A <- data.frame('Area' = c(4, 6, 5),
                'flow' = c(1, 1, 1))
B <- data.frame('Area' = c(6, 8, 4),
                'flow' = c(1, 2, 1))
files <- list(A, B)
frames <- list('A', 'B')

我要执行的操作是按“流”变量对数据进行排序,然后为每个数据点代表的“流”和“面积”的总和部分添加列,最后再添加两列累积百分比每个变量。

当前,我将此用于循环:

sort_files <- list()
n <- 1
for(i in files){
  name <- frames[n]
  nom <- paste(name,'_sorted', sep = '')
  data <- i[order(-i$flow),]
  area <- sum(i$Area)
  total <- sum(i$flow)
  data$area_portion <- (data$Area/area)*100
  data$flow_portion <- (data$flow/total)*100
  data$cum_area <- cumsum(data$area_portion)
  data$cum_flow <- cumsum(data$flow_portion)
  assign(nom, data)
  df <- get(paste(name,'_sorted', sep = ''))
  sort_files[[nom]] <- df
  n <- n + 1
}

这是可行的,但看起来过于复杂和丑陋,我相信它的运行速度将比更好的脚本慢得多。

如何简化和整理以上代码?

这是预期的输出:

sort_files

$`A_sorted`
  Area flow area_portion flow_portion  cum_area  cum_flow
1    4    1     26.66667     33.33333  26.66667  33.33333
2    6    1     40.00000     33.33333  66.66667  66.66667
3    5    1     33.33333     33.33333 100.00000 100.00000

$B_sorted
  Area flow area_portion flow_portion  cum_area cum_flow
2    8    2     44.44444           50  44.44444       50
1    6    1     33.33333           25  77.77778       75
3    4    1     22.22222           25 100.00000      100

2 个答案:

答案 0 :(得分:13)

使用lapply遍历filesdplyr mutate添加新列

library(dplyr)

setNames(lapply(files, function(x) 
          x %>%
            arrange(desc(flow)) %>%
            mutate(area_portion = Area/sum(Area)*100, 
                   flow_portion = flow/sum(flow) * 100, 
                   cum_area = cumsum(area_portion),
                   cum_flow = cumsum(flow_portion))
),paste0(frames, "_sorted"))


#$A_sorted
#  Area flow area_portion flow_portion  cum_area  cum_flow
#1    4    1     26.66667     33.33333  26.66667  33.33333
#2    6    1     40.00000     33.33333  66.66667  66.66667
#3    5    1     33.33333     33.33333 100.00000 100.00000

#$B_sorted
#  Area flow area_portion flow_portion  cum_area cum_flow
#1    8    2     44.44444           50  44.44444       50
#2    6    1     33.33333           25  77.77778       75
#3    4    1     22.22222           25 100.00000      100

或者完全采用tidyverse的方式,我们可以使用lapply更改map和使用setNames更改set_names

library(tidyverse)

map(set_names(files, str_c(frames, "_sorted")), 
  . %>% arrange(desc(flow)) %>%
  mutate(area_portion = Area/sum(Area)*100, 
         flow_portion = flow/sum(flow) * 100, 
         cum_area = cumsum(area_portion),
         cum_flow = cumsum(flow_portion)))

根据@Moody_Mudskipper的一些指示,更新了tidyverse方法。

答案 1 :(得分:7)

您还可以先定义一个函数..

f <- function(data) {

  # sort data by flow
  data <- data[order(data['flow'], decreasing = TRUE), ]

  # apply your functions
  data["area_portion"] <- data['Area'] / sum(data['Area']) * 100
  data["flow_portion"] <- data['flow'] / sum(data['flow']) * 100
  data["cum_area"] <- cumsum(data['area_portion'])
  data["cum_flow"] <- cumsum(data['flow_portion'])
  data
  }

..并使用lapplyf应用于您的列表

out <- lapply(files, f)
out
#[[1]]
#  Area flow area_portion flow_portion  cum_area  cum_flow
#1    4    1     26.66667     33.33333  26.66667  33.33333
#2    6    1     40.00000     33.33333  66.66667  66.66667
#3    5    1     33.33333     33.33333 100.00000 100.00000

#[[2]]
#  Area flow area_portion flow_portion  cum_area cum_flow
#2    8    2     44.44444           50  44.44444       50
#1    6    1     33.33333           25  77.77778       75
#3    4    1     22.22222           25 100.00000      100

如果要更改out的名称,可以使用setNames

out <- setNames(lapply(files, f), paste0(c("A", "B"), "_sorted"))
# or
# out <- setNames(lapply(files, f), paste0(unlist(frames), "_sorted"))