Stack Overflow Asked by Dylan Ong on January 5, 2022
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
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:
Answered by akrun on January 5, 2022
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP