R-向量中特定值的嵌套循环
一般来说,我对R/中的循环非常陌生,在其他地方找不到答案 我使用嵌套循环将两个向量的值粘贴到超链接中。虽然我只希望有三个输出字符串,但我总共收到九个字符串。也许这真的很容易,但任何输入都是非常感谢的R-向量中特定值的嵌套循环,r,loops,R,Loops,一般来说,我对R/中的循环非常陌生,在其他地方找不到答案 我使用嵌套循环将两个向量的值粘贴到超链接中。虽然我只希望有三个输出字符串,但我总共收到九个字符串。也许这真的很容易,但任何输入都是非常感谢的 **Example:** start <- c("Value1", "Value2", "Value3") end <- c("Value1.1", "Value2.1", "Value3.1") summary <- c() for (i in start) {
**Example:**
start <- c("Value1", "Value2", "Value3")
end <- c("Value1.1", "Value2.1", "Value3.1")
summary <- c()
for (i in start) {
for(j in end) {
summary[i] <- print(paste('This is a Hyperlink Text',
i, 'here it continues', j ,'here it ends'))
}
}
**Actual Output:**
[1] "This is a Hyperlink Text **Value1** here it continues **Value1.1** here it ends"
[1] "This is a Hyperlink Text **Value1** here it continues **Value2.1** here it ends"
[1] "This is a Hyperlink Text **Value1** here it continues **Value3.1** here it ends"
[1] "This is a Hyperlink Text **Value2** here it continues **Value1.1** here it ends"
[1] "This is a Hyperlink Text **Value2** here it continues **Value2.1** here it ends"
[1] "This is a Hyperlink Text **Value2** here it continues **Value3.1** here it ends"
[1] "This is a Hyperlink Text **Value3** here it continues **Value1.1** here it ends"
[1] "This is a Hyperlink Text **Value3** here it continues **Value2.1** here it ends"
[1] "This is a Hyperlink Text **Value3** here it continues **Value3.1** here it ends"
**Desired ouput:**
"This is a Hyperlink Text **Value1** here it continues **Value1.1** here it ends"
"This is a Hyperlink Text **Value1** here it continues **Value2.1** here it ends"
"This is a Hyperlink Text **Value1** here it continues **Value3.1** here it ends"
**示例:**
开始如果值具有相同的索引,则不需要嵌套循环。它的设置方式必然为您提供i x j行。因此,在这里,只使用一个索引,单循环:
for (i in 1:length(start)) {
summary[i] <- print(paste('This is a Hyperlink Text',
start[i], 'here it continues', end[i] ,'here it ends'))
for(1中的i:长度(起始)){
这样怎么样
start <- c("Value1", "Value2", "Value3")
end <- c("Value1.1", "Value2.1", "Value3.1")
summary <- c()
for (i in seq_along(start)) {
summary[i] <- paste('This is a Hyperlink Text',
start[i], 'here it continues', end[i] ,'here it ends')
}
print(summary)
非常感谢您的快速回答!这非常有效,我现在理解了我的错误。很高兴我能帮上忙!
library(purrr)
purrr:::map2(start,end,~ paste('This is a Hyperlink Text', .x, 'here it continues', .y ,'here it ends'))
mapply(function(x, y) paste('This is a Hyperlink Text', x, 'here it continues', y ,'here it ends'),
x = start, y = end)
# Value1
# "This is a Hyperlink Text Value1 here it continues Value1.1 here it ends"
# Value2
# "This is a Hyperlink Text Value2 here it continues Value2.1 here it ends"
# Value3
# "This is a Hyperlink Text Value3 here it continues Value3.1 here it ends"