title: how to fix this error "Error in rep(yes, length.out = len) : attempt to replicate an object of type 'S4'"
body: <p>I have 2500 raster data and each raster can contain 1 or 2 or 3 layer. The problem is the best layer(the layer contain minimum NA values) for each raster need to be selected and I'd like to use R for this purpose. the sample data (contain 4 raster file) is uploaded <a href="https://drive.google.com/drive/folders/1O0W4cKsw0GrVUSHmc82ED2BoD1w0KAe2?usp=sharing" rel="nofollow noreferrer">here</a>:
  in the first step, I'd like to select the best layer from the raster files that contain just 3 layers.
  I use this code:</p>
  <pre><code>list_files &lt;- list.files(pattern = &quot;.tif&quot;)
  file_name &lt;- paste0(&quot;best_layer&quot; , list_files)
  library(raster)
  
  for(i in 1:length(list_files)){
    r &lt;- stack(list_files[i])
    len &lt;- nlayers(r)
    if(len!=3)
      next
    r_1 &lt;- sum(is.na(as.matrix(r[[1]])))
    r_2 &lt;- sum(is.na(as.matrix(r[[2]])))
    r_3 &lt;- sum(is.na(as.matrix(r[[3]])))
    ifelse((r_1 &lt; r_2 &amp; r_1 &lt; r_3),print(&quot;layer1&quot;),
           ifelse((r_2 &lt; r_1 &amp; r_2 &lt; r_3)
                  ,print(&quot;layer_2&quot;)
                  ,print(&quot;layer_3&quot;)))
  }
  </code></pre>
  <p>and the result is:</p>
  <pre><code>[1] &quot;layer_1&quot;
  [1] &quot;layer_1&quot;
  [1] &quot;layer_2&quot;
  [1] &quot;layer_2&quot;
  </code></pre>
  <p>But when i change the ifelse to write best raster layer likes this code:</p>
  <pre><code>for(i in 1:length(list_files)){
    r &lt;- stack(list_files[i])
    len &lt;- nlayers(r)
    if(len!=3)
      next
    r_1 &lt;- sum(is.na(as.matrix(r[[1]])))
    r_2 &lt;- sum(is.na(as.matrix(r[[2]])))
    r_3 &lt;- sum(is.na(as.matrix(r[[3]])))
    ifelse((r_1 &lt; r_2 &amp; r_1 &lt; r_3),writeRaster(x = r[[1]], filename = file_name[i], format = 'GTiff'),
           ifelse((r_2 &lt; r_1 &amp; r_2 &lt; r_3)
                  ,writeRaster(x = r[[2]], filename = file_name[i], format = 'GTiff')
                  ,writeRaster(x = r[[3]], filename = file_name[i], format = 'GTiff')))
  }
  </code></pre>
  <p>I expect R create 4 tiff file with the best layer but R creates just the first file and gave me this error:</p>
  <blockquote>
  <p>Error in rep(yes, length.out = len) :
  attempt to replicate an object of type 'S4'</p>
  </blockquote>
  <p>how can I fix this error???
  Thanks.</p>