1

I have a dataset with 2 columns which consists of a boolean column and values.I will like to find the sum of the F value using while loop.Coe shown below but giving error:

 sum <- 0
FM <- 0
 idx <- 1
while ( idx <= nrow(dataset)){
if(subset(dataset,boolean=="F")){
sum <- sum + dataset [ idx,"value" ]
FM <- FM + 1

}

  idx <- idx + 1
}
 print(sum)

error message is : Error in idx : object 'idx' not found

Omat
  • 67
  • 1
  • 1
  • 4
  • `if` requires a single logical, this code is very likely to give multiple values, and I have no idea if those values will be logical. – r2evans Jan 30 '20 at 22:59
  • This might be easier for us to understand if you make this question reproducible. This includes sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`) and expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Jan 30 '20 at 23:01
  • Thank you for your response.example shown below:data.frame(boolean= T,F,T,T,F....,value=8,16,4,12,9,.....).Expected output is to sum the value for F using while loop – Omat Jan 30 '20 at 23:18

1 Answers1

0

If you count sum of logical values, you get count how many TRUE values are present. Since in this case as you want to count number of FALSE values we can negate the values and then use sum.

sum(!df$boolean)
#[1] 2

However, I guess you want this in a while loop. You can iterate over every value in boolean column, check if it is FALSE and increment the count.

i <- 1
FM <- 0
while(i <= nrow(df)) {
  if(!df$boolean[i]) 
     FM <- FM + 1
   i <- i + 1
}
FM
#[1] 2

We can also do this without if condition

while(i <= nrow(df)) {
   FM <- FM + !df$boolean[i]
   i <- i + 1
}

data

df <- data.frame(boolean= c(TRUE,FALSE,TRUE,TRUE,FALSE),value=c(8,16,4,12,9))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213