避免嵌套循环但使用 (l)apply 迭代 2 个值? [英] Avoiding nested loops but iterate over 2 values using (l)apply?

查看:25
本文介绍了避免嵌套循环但使用 (l)apply 迭代 2 个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 R 中更好地编写优雅的代码,并试图避免编写嵌套循环,但无法找出 (l)apply 解决我的问题的方法.

I'd like to get better at writing elegant code in R, and am trying to avoid writing nested loops, but cannot figure out an (l)apply solution to my problem.

我有一组配对文件,每个文件都有两个与之关联的变量 - 一个名称和一个数字.文件名很长,所以我想生成一个文件名向量,然后我自己的自定义下游函数可以访问这些文件名,以便将它们读入数据帧、绘图等.

I have a set of paired files, each of which has two variables associated with them - a name and a number. The filenames are long, so I'd like to generate a vector of filenames that can then be accessed by my own custom downstream function for reading them into a dataframe, plotting, etc.

例如,文件看起来像:

 5_simulationA.k  5_simulationA.b
10_simulationA.k 10_simulationA.b
 5_simulationB.k  5_simulationB.b
10_simulationB.k 10_simualtionB.b

.k"和.b"文件是配对的,必须保持在一起以进行下游处理.

The ".k" and ".b" files are mates of a pair and must stay together for downstream processing.

我可以通过编写一个看起来像这样的嵌套循环来读取这些文件

I could read in these files by writing a nested loop that would look something like,

K_files = c()
B_files = c()

for (i in c(A,B,C)){ # iterate over letter variable
    for (n in c(5,10,15)){ #iterate over numbers of the files
        k_filename = paste(n, "_simulation", i, ".k")
        b_filename = paste(n, "_simulation", i, ".b")
        K_files = c(K_files, k_filename)
        B_files = c(B_files, b_filename)
    }
}

这当然非常丑陋且不喜欢 R.我很想找到一种方法来使用非常强大的 apply 或 lapply 语句,或者任何其他人可能拥有的任何其他优雅的解决方案.谢谢!

This is of course very ugly and un-R-like. I would love to find a way to do this with the very powerful apply or lapply statements, or any other elegant solutions anyone might have. Thanks!

推荐答案

Base R function outer 就是针对这类问题的.

Base R function outer is meant for this kind of problem.

L <- c("A", "B", "C")
N <- c(5, 10, 15)

f <- function(i, n, e) paste0(n, "_simulation", i, e)
sapply(c(".k", ".b"), function(.e) outer(L, N, f, e = .e))
#     .k                 .b                
# [1,] "5_simulationA.k"  "5_simulationA.b" 
# [2,] "5_simulationB.k"  "5_simulationB.b" 
# [3,] "5_simulationC.k"  "5_simulationC.b" 
# [4,] "10_simulationA.k" "10_simulationA.b"
# [5,] "10_simulationB.k" "10_simulationB.b"
# [6,] "10_simulationC.k" "10_simulationC.b"
# [7,] "15_simulationA.k" "15_simulationA.b"
# [8,] "15_simulationB.k" "15_simulationB.b"
# [9,] "15_simulationC.k" "15_simulationC.b"

这篇关于避免嵌套循环但使用 (l)apply 迭代 2 个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆