簡體   English   中英

mean(,na.rm = TRUE) 返回 NA 和警告消息

[英]mean(,na.rm = TRUE) returns NA and 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]“你好”名稱:字符:盧克天行者 C-3PO R2-D2 達斯維德 [1]“你好”數字的平均值是:174.358。 ans[ypos] <- rep(yes, length.out = len)[ypos] 中的錯誤:替換長度為零另外:警告消息:在 rep(yes,length.out = len) 中:'x' 是 NULL 所以結果將是 NULL

我對 R 很陌生。 出於某種原因,我的 mean() function 在拋出錯誤之前只返回部分平均值。 我試着寫

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

在 for 循環之外,它返回了 NA 和錯誤/警告。

任何幫助將不勝感激

我們可以將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: 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM