2014-04-24 23 views
0

我對R相當陌生,而且在遇到一個函數時遇到問題。我想將data.frame中的三列從字符轉換爲數字。它們大部分由數字組成,其中分佈有幾個「不可用」條目。我意識到這些,並且我希望他們在沒有看到警告的情況下強制要求新手,所以我使用了suppressWarnings()函數。將字符變量強制轉換爲數字而不發出警告

這裏是我的代碼:

suppressWarnings(class(dataframe[,2]) <- "numeric") 
suppressWarnings(class(dataframe[,3]) <- "numeric") 
suppressWarnings(class(dataframe[,4]) <- "numeric") 
print(apply(dataframe,2,class)) 

的是,該被打印的結果是我的問題:

  1   2   3   4 
"character" "character" "character" "character" 

因此,它似乎並沒有被改變類!爲什麼是這樣?

當我做到這一點,但不影響的警告,就像這樣:

class(dataframe[,2]) <- "numeric" 
    class(dataframe[,3]) <- "numeric" 
    class(dataframe[,4]) <- "numeric" 
    print(apply(dataframe,2,class)) 

我得到的結果相同,但與警告消息:

  1   2   3   4 
"character" "character" "character" "character" 
Warning messages: 
1: In class(dataframe[, 2]) <- "numeric" : NAs introduced by coercion 
2: In class(dataframe[, 3]) <- "numeric" : NAs introduced by coercion 
3: In class(dataframe[, 4]) <- "numeric" : NAs introduced by coercion 

所以它不是報警抑制是這樣的問題。它必須是apply()函數,但我不明白爲什麼它會錯誤地顯示類。

任何意見或援助,將不勝感激!

+0

你嘗試過'dataframe [,2] < - as.numeric(dataframe [,2])'嗎? – hrbrmstr

+0

我確實嘗試過,並且得到了相同的輸出結果。 – MsTiggy

+0

你可以粘貼一個'dput(dataframe)'輸出(甚至是'dataframe'的擴展'head')嗎? – hrbrmstr

回答

2

這裏的問題是apply;請參閱?apply中的「詳細信息」:「如果X不是數組[..],apply嘗試通過as.matrix將其強制轉換爲數組,如果它是二維的(例如數據幀)。」然後查看「?as.matrix中的詳細信息:」如果只有原子列和任何非(數字/邏輯/複合)列,數據框的方法將返回字符矩陣「。因此,儘管您轉換爲數字作品,利用檢查他們的類時apply超過列「環」第一脅迫的數據幀爲一個字符矩陣

一個小例子首先創建一個玩具數據幀:。

df <- data.frame(x1 = c("a", "b"), 
       x2 = c("Not Available", 2), 
       x3 = c("Not Available", 3), 
       x4 = c(4, "Not available")) 

轉換選擇的列到數字,就像你在你的問題所做的那樣:

df[, 2:4] <- lapply(df[ , 2:4], function(x) as.numeric(x)) 
str(df) 

如果得到的數據幀被強制轉換爲矩陣,爲apply會做,它是強制轉換爲字符矩陣

str(as.matrix(df)) 
# chr [1:2, 1:4] "a" "b" NA " 2" NA " 3" " 4" NA 
# - attr(*, "dimnames")=List of 2 
# ..$ : NULL 
# ..$ : chr [1:4] "x1" "x2" "x3" "x4" 

而不是使用apply檢查類的列的,您可以嘗試:

sapply(df, class) 
#   x1   x2   x3   x4 
# "character" "numeric" "numeric" "numeric" 

str(df) 
# 'data.frame': 2 obs. of 4 variables: 
# $ x1: chr "a" "b" 
# $ x2: num NA 2 
# $ x3: num NA 3 
# $ x4: num 4 NA 
相關問題