gpt4 book ai didi

r - 双 for 循环只返回最后一项

转载 作者:行者123 更新时间:2023-12-02 03:20:26 26 4
gpt4 key购买 nike

我有以下列表(实际列表更大,但我将其缩小以便更容易理解:

clubs <- c("Arsenal", "Chelsea", "Southhampton")

我想做的是遍历俱乐部并找到所有对手。所以在南安普顿的情况下:

[1] "Southhampton VS Arsenal"
[1] "Southhampton VS Chelsea"
[1] "Southhampton VS Southhampton

我想为所有俱乐部(阿森纳和切尔西)这样做。

因此我写了下面的代码:

 distances <- function(list) {

#list for storing purposes
list_new <- c()
count <- length(list)

#perform one loop for each club
for (j in count) {

for (i in list){

#get the first club
var <- list[j]

#fetch list item
var_opponent <- list(i)

#print(var_opponent)
var_total <- paste0(var, " VS ", var_opponent)

print(var_total)

list_new <- c(list_new, var_total)

}

}

}

但它并不完全有效,因为这是我的输出:

> distances(clubs)
[1] "Southhampton VS Arsenal"
[1] "Southhampton VS Chelsea"
[1] "Southhampton VS Southhampton"

谁能告诉我为什么我只得到最后一家具乐部的记录?

最佳答案

您的代码中有不止一个错误。

您首先需要了解的是,R 中的 for 循环会遍历一个元素列表。让我们假设您的代码中的计数为 3。第一个 for 循环将是

for(j in 3)

因此 j 将是列表中由单个 3 组成的所有元素。在下一个 for 循环中,您以正确的方式遍历列表。

for(i in list)

将列表中的每个俱乐部分配给变量 i 一次一个。因此俱乐部名称(不是俱乐部名称的索引)存储在变量 i 中,您不需要索引列表来获取俱乐部名称。

第二个错误是用“索引”列表

 list(i)

这与传递给函数的列表参数没有任何关系。这是对列表函数的调用,这会将变量 i 放入列表中。

你的代码应该是这样的

distances <- function(clubs) {

list_new <- c()

#perform one loop for each club
for (club1 in clubs) {

for (club2 in clubs){


var_total <- paste0(club1, " VS ", club2)

print(var_total)

list_new <- c(list_new, var_total)

}

}

}

这是解决问题的更好方法

distances <-  function(clubs) combn(rep(clubs,2),2,function(x) paste(x[1] ,"VS", x[2]))

关于r - 双 for 循环只返回最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com