0

Here is my code and the error/warning message

library(dplyr)

df_sw = as.data.frame(starwars)

df_sw = df_sw[1:11]
final = ""
print(mean(df_sw[,1],trim = 0, na.rm = TRUE))
for(i in 1:ncol(df_sw)){
  print("hello")
  cat(colnames(df_sw)[i], ": ",ifelse(is.numeric(df_sw[1,i]),cat("numeric the mean is: ",mean(df_sw[,i],trim = 0, na.rm = TRUE)),"character: "))
  for(b in 1:4){
    cat(df_sw[b,i], " ")
  }
}

[1] "hello" name : character: Luke Skywalker C-3PO R2-D2 Darth Vader [1] "hello" numeric the mean is: 174.358. Error in ans[ypos] <- rep(yes, length.out = len)[ypos] : replacement has length zero In addition: Warning message: In rep(yes, length.out = len) : 'x' is NULL so the result will be NULL

I am very new to R. For some reason, my mean() function only returns part of the mean before throwing an error. I tried writing the

mean(df_sw[,I], na.rm = TRUE)

outside the for loop, and it returned both NA and the error/warning.

Any help would be greatly appreciated

Dylan Ong
  • 786
  • 2
  • 6
  • 14
  • I believe I checked beforehand if the column was non-numeric by checking the first value of each column. – Dylan Ong Jul 24 '20 at 23:09
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 24 '20 at 23:11
  • 1
    Never combine `ifelse` and `cat`. `ifelse` deals in vectors: vectors of logical, and vectors of "yes" and "no". `cat` always returns `NULL`. – r2evans Jul 24 '20 at 23:17

1 Answers1

1

We could change the ifelse to if/else

for(i in seq_along(df_sw)){
   
   # // if the column is numeric
   if(is.numeric(df_sw[,i])) {
   # // print the mean
   cat(colnames(df_sw)[i], ": numeric the mean is: ",
             mean(df_sw[,i],trim = 0, na.rm = TRUE), "\n")
   } else {
    # // print that it is a character column
     cat(colnames(df_sw)[i], ": character: \n")
   
    }
 }

#name : character: 
#height : numeric the mean is:  174.358 
#mass : numeric the mean is:  97.31186 
#hair_color : character: 
#skin_color : character: 
#eye_color : character: 
#birth_year : numeric the mean is:  87.56512 
#sex : character: 
#gender : character: 
#homeworld : character: 
#species : character: 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks that works. Is there a reason why my earlier example didn't work the same way? – Dylan Ong Jul 24 '20 at 23:15
  • 1
    @green142f There is no `return` value in `cat` i.e. `out <- cat("153\n"); out# NULL` while the `ifelse` requires each of the arguments to have same length and `length(NULL)` is 0 – akrun Jul 24 '20 at 23:18