这是我的代码和错误/警告消息
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]“你好” 名称:字符:卢克·天行者C-3PO R2-D2达斯·维达[1]“你好” 数字平均值是:174.358。 ans [ypos] <-rep中的错误(是,length.out = len)[ypos]: 替换的长度为零 另外:警告消息: 在rep(yes,length.out = len)中:'x'为NULL,因此结果为NULL
我对R很陌生。由于某种原因,我的mean()函数在抛出错误之前仅返回均值的一部分。我尝试写
mean(df_sw[,I], na.rm = TRUE)
在for循环之外,它同时返回NA和错误/警告。
任何帮助将不胜感激
答案 0 :(得分:1)
我们可以将ifelse
更改为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: