for loop(i,j) - 获得i = 1且j = 1,然后i = 2且j = 2等

时间:2015-01-26 19:56:57

标签: r for-loop

我有两个文件列表,我想通过我创建的自定义函数将其合并到一个文件中。

在以下示例中,自定义函数可以替换为此行print(paste(i, j))。我使用打印/粘贴来说明我的观点。

l1 <- c("file1a", "file1b")
l2 <- c("file2a", "file2b")

for(i in seq(along = l1)) {
for(j in seq(along = l2)) {
print(paste(i, j))
}
}

# [1] "1 1"
# [1] "1 2"
# [1] "2 1"
# [1] "2 2"

我怎样才能获得

# "1" "1" file1a and file2a where a = 1

# "2" "2" file1b and file2b where b = 2

因此,请忽略

# "1 2" file1a and file2b where a = 1 and b = 2

# "2 1" file1b and file2a where a = 1 and b = 2

1 个答案:

答案 0 :(得分:1)

这就是你要找的东西吗?

for (pair in Map(c,1:4,1:4)) print(paste(pair[1],pair[2]))
#[1] "1 1"
#[1] "2 2"
#[1] "3 3"
#[1] "4 4"

另一个例子:

for (pair in Map(c,l1,l2)) print(paste(pair[1],pair[2]))
#[1] "file1a file2a"
#[1] "file1b file2b"

您也可以这样做:

Map(paste,l1,l2)
#$file1a
#[1] "file1a file2a"
#
#$file1b
#[1] "file1b file2b"
相关问题