2015-09-28 38 views
0

我正在嘗試對dataframe列進行計算,但由於該列包含級別,因此儘管使用了droplevels命令(從this後),但它們仍保持失敗狀態。我在做什麼錯在這裏:從數據框中刪除級別失敗

csv <- data.frame(col1 = c("question",1,23,2,5,6), col2 = c("question",5,6,7,3,"")) 
csv[csv==''] <- NA 
csv <- csv[-c(1),] #remove the header question row because this screws up numeric calculations 
csv <- droplevels(csv) 
csv[,1] <- 7-csv[,1] 

我得到:

Warning message: 
In Ops.factor(7, csv[, 1]) : ‘-’ not meaningful for factors 

回答

5

刪除水平是不同的命令。你不再需要因素。嘗試使用as.numeric(as.character(mycol))準備算術列。

csv[] <- lapply(csv, function(x) as.numeric(as.character(x))) 

我將它封裝在lapply中以轉換所有列。

結果:

csv[,1] <- 7-csv[,1] 
    col1 col2 
2 6 5 
3 -16 6 
4 5 7 
5 2 3 
6 1 NA 

我們下降的水平,當我們有未使用的因素。不要將它們轉換爲數字。例如:

fac <- factor(c("a", "b")) #factor with two levels 'a' and 'b' 
fac 
#[1] a b 
#Levels: a b 

fac.one <- fac[1] #Just the first element of 'fac' which is 'a'. 
fac.one 
#[1] a 
#Levels: a b  # <-- There are still two levels. 'b' is not used. 

當我們製造fac.one時,我們只有一個元素。但舊的因素水平仍然存在。如果我們只想要在對象中使用的因素,我們使用droplevels像這樣:

droplevels(fac.one) 
#[1] a 
#Levels: a  #One factor remains. 'b' is dropped