0

I am trying to create a simple function to group the data I have based on a single variable in the data frame, called Depths.

I created the following function, but I'm still having issues.

vecki <- as.array(rep(0,50))

group_AtoD <- function(x){

  i<- 1

for(i in 1:55){


  if(x$Depths..m.[i] >= 0 & x$Depths..m. <= 1237.5){

    vecki[i] <- "D"
    i<- i+1

  }else if(x$Depths..m.[i] > 1237.5 & x$Depths..m.[i] <= 2475){

    vecki[i] <- "C"
    i<- i+1

  }else if(x$Depths..m.[i] > 2475 & x$Depths..m.[i] <= 3712.5){

    vecki[i] <- "B"
    i<- i+1

  } else if(x$Depths..m.[i] > 3712.5 & x$Depths..m.[i] <= 4950) {

    vecki[i] <- "A"
    i<- i+1
  }

}
return(cbind(x,vecki))

}

I get the following warning: "the condition has length > 1 and only the first element will be used"

I have seen the error appearing on other threads, but none of the advice or answers helped me in any way.

It ends up running, but the vecki vector I am creating and cbinding to my original data frame - in order to group - has only the value D. I ran i in the command line and it is 56 - so it is iterating fine.

Any help would be much appreciated.

Thanks!

EDIT:: I have solved the problem using a similar function to the one below and utilising which(). I just want to know, for educational purposes why the following function isnt working properly. Thanks again.

h3ab74
  • 318
  • 3
  • 16

1 Answers1

0

You could definitely make this a lot simpler for yourself by not using loops. As @zx8754 mentioned, ifelse is very useful. I'm also a fan of case_when from dplyr. For example:

library(dplyr)

my_data <- data_frame(Depths..m. = c(1,4,6,1345, 1211,1,4920,6000,2110,1300,11,2600))

group_AtoD <- function(x){
  mutate(x, ID = case_when(
    Depths..m. >= 0 & Depths..m. <= 1237.5 ~ "D",
    Depths..m. > 1237.5 & Depths..m. <= 2475 ~ "C",
    Depths..m. > 2475 & Depths..m. <= 3712.5 ~ "B",
    Depths..m. > 3712.5 & Depths..m. <= 4950 ~ "A"
  ))
}

group_AtoD(my_data)
#> # A tibble: 12 x 2
#>    Depths..m. ID   
#>         <dbl> <chr>
#>  1          1 D    
#>  2          4 D    
#>  3          6 D    
#>  4       1345 C    
#>  5       1211 D    
#>  6          1 D    
#>  7       4920 A    
#>  8       6000 <NA> 
#>  9       2110 C    
#> 10       1300 C    
#> 11         11 D    
#> 12       2600 B
AndS.
  • 7,748
  • 2
  • 12
  • 17