I am new at R coding and struggling with my for loop system. I have a data frame with the frequency of 20 zones entered as columns, and the value for each ID as rows. I want to code that for each value, if value >0, add 1 to unique visited
Here is what I coded for each zone (which takes a lot of space and time)
for (index in 1:length(OFTUpt$Zone1)){
if (OFTUpt$Zone1[index]>0){
OFTUpt$UniqueVisited[index]= OFTUpt$UniqueVisited[index] 1
}
}
Here is the code I had for the for loop, but my second for loop does not seem to have the right parameters?
for (i in 3:length(OFT1Upt)){
print (OFT1Upt[i])
for (v in length(OFT1Upt[i])){
#here would go my = 1 line of code
}
}
Thank you!
EDIT: Here is the dataset. https://github.com/SoundsF1shy/Odour-cue-and-Exploration
CodePudding user response:
If I am understanding you correctly, you want to sum all the "S" columns (S1:S20) that have a value > 0. If this is what you need to do, try the following code (that does not involve loops):
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