r语言 - 遍历结果列表以修改数据帧中的列



下面是我笨拙的(?)过程尝试,将函数fastNonDominatedSorting的结果从包nsga2R附加到数据帧。也许有一种更简单的方法可以将结果列表附加到数据框架中?

库(nsga2R)

df <- data.frame(
x = c(0,0.5,0.5,1.0)
, y = c(0,1.0,1.0,1.0)
)
matrix <- data.matrix(df)
mo_sorting_results <- fastNonDominatedSorting(matrix)
rank <- 1
df$rank <- 0
for(a_list in mo_sorting_results) {
for(list_element in a_list) {
print(list_element)
df[list_element,]$rank <- rank 
}
rank <- rank + 1
}
df

当我理解你的方法正确时,从mo_sorting_results

library("nsga2R")
mo_sorting_results <- fastNonDominatedSorting(matrix)
mo_sorting_results
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2 3
# 
# [[3]]
# [1] 4

你想要每一个列表级别增加一个秩,像这样吗?

df$rank <- unlist(mapply(rep, seq(mo_sorting_results), lengths(mo_sorting_results)))
df
#     x y rank
# 1 0.0 0    1
# 2 0.5 1    2
# 3 0.5 1    2
# 4 1.0 1    3
基准

这将会快15倍。

forloop <- function() {
rank <- 1
df$rank <- 0
for (a_list in mo_sorting_results) {
for (list_element in a_list) {
df[list_element,]$rank <- rank 
}
rank <- rank + 1
}
}
mapply1 <- function() {
unlist(mapply(rep, seq(mo_sorting_results), lengths(mo_sorting_results)))
}
microbenchmark::microbenchmark(forloop(), mapply1())
# Unit: microseconds
#      expr     min       lq     mean  median      uq     max neval cld
# forloop() 523.290 533.7510 550.6793 539.619 548.804 750.619   100   b
# mapply1()  31.893  33.9335  37.1739  35.975  37.251  90.065   100  a