R:在数据框中的另一个for循环中缩进的循环

R: For loops indented in another for loop in data frame

我是 R 编码的新手,正在为我的 for 循环系统苦苦挣扎。 我有一个数据框,其中 20 个区域的频率作为列输入,每个 ID 的值作为行。我想为每个值编写代码,如果值 >0,则将 1 添加到唯一访问

这是我为每个区域编写的代码(这需要很多 space 和时间)

for (index in 1:length(OFTUpt$Zone1)){
  if (OFTUpt$Zone1[index]>0){
   OFTUpt$UniqueVisited[index]= OFTUpt$UniqueVisited[index]+1 
  }
}

这是我的 for 循环代码,但我的第二个 for 循环似乎没有正确的参数?

for (i in 3:length(OFT1Upt)){
    print (OFT1Upt[i])
  for (v in length(OFT1Upt[i])){
    #here would go my =+ 1 line of code 
  }
}

谢谢!

编辑:这是数据集。 https://github.com/SoundsF1shy/Odour-cue-and-Exploration

如果我没有理解错的话,您想计算所有值 > 0 的“S”列 (S1:S20)。如果这是您需要做的,请尝试以下代码(不涉及循环):


OFTUpt$UniqueVisited <- rowSums(OFTUpt[4:23] > 0)

head(OFTUpt)
# > head(OFTUpt)
# ID    Sex Total.Distance..cm. S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 S11 S12 S13 S14 S15 S16 S17 S18 S19 S20 UniqueVisited
# 1  1 Female             425,096  6  7  7  6  6  4  6  4  1   5   4   4   4   3   5   3   2   4   6   5            20
# 2  2   Male             659,433 22 19 11 13 18  9  2  0  2   7   9   2   0   0   5   7   4   3   3   7            17
# 3  3 Female             804,481 15 12 10 10  6 19  4  4  2   8  21   4   4   1  10  12  11  13  11  12            20
# 4  4   Male             620,869  8  7  8 12 26  7  5  3  3   9   5   5   4   2   7   5   6   5   4   8            20
# 5  5 Female             632,211  6  4  4  4  4  8  2  1  2   4   9   2   2   3   6  21  19  14  14  14            20
# 6  6   Male             246,109  5  7  4  2  2  4  3  4  2   2   5   2   1   1   2   3   2   1   2   2            20