for loop (i, j) -- 获取 i=1 和 j=1 然后 i=2 和 j=2,等等
for loop (i, j) -- obtain i=1 and j=1 then i=2 and j=2, etc
我有两个文件列表,我想通过我创建的自定义函数将它们合并到一个文件中。
在下面的例子中,自定义函数可以用这一行代替print(paste(i, j))
。我正在使用 print/paste 来说明我的观点。
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
这是你要找的吗?
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"
我有两个文件列表,我想通过我创建的自定义函数将它们合并到一个文件中。
在下面的例子中,自定义函数可以用这一行代替print(paste(i, j))
。我正在使用 print/paste 来说明我的观点。
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
这是你要找的吗?
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"