2014-02-13 15 views
3

我有一些列的數據幀:代碼多個級別2因子標籤

  • ,我想變換成一個因子,
  • 其中不同級別被編碼爲-2, -1, 0, 1, 2, 3, 4
  • 爲此,我想水平被打成01此約定如下:

    -2 = 1 
    -1 = 1 
    0 = 0 
    1 = 1 
    2 = 1 
    3 = 1 
    4 = 0 
    

我有以下代碼:

#Convert to factor 
dat[idx] <- lapply(dat[idx], factor, levels = -2:4, labels = c(1, 1, 0, 1, 1, 1, 0)) 

#Drop unused factor levels 
dat <- droplevels(dat) 

這工作,但它給了我以下警告:

In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels, : 
duplicated levels in factors are deprecated 

我嘗試下面的代碼(每阿難Mahto的建議),但沒有運氣:

levels(dat[idx]) <- list(`0` = c(0, 4), `1` = c(-2, -1, 1, 2, 3)) 

我覺得必須有更好的方法來做到這一點,有什麼建議嗎?

我的數據是這樣的:

structure(list(Timestamp = structure(c(1380945601, 1380945603, 
1380945605, 1380945607, 1380945609, 1380945611, 1380945613, 1380945615, 
1380945617, 1380945619), class = c("POSIXct", "POSIXt"), tzone = ""), 
FCB2C01 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), RCB2C01 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C02 = c(1, 1, 1, 1, 1, 1, 
1, 1, 1, 1), RCB2C02 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C03 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), RCB2C03 = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), FCB2C04 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), RCB2C04 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C05 = c(1, 1, 1, 1, 1, 1, 
1, 1, 1, 1), RCB2C05 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C06 = c(1, 
1, 1, 1, 1, 1, 1, 1, 1, 1), RCB2C06 = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), FCB2C07 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), RCB2C07 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C08 = c(1, 1, 1, 1, 1, 1, 
1, 1, 1, 1), RCB2C08 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), FCB2C09 = c(1, 
1, 1, 1, 1, 1, 1, 1, 1, 1), RCB2C09 = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), FCB2C10 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), RCB2C10 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Timestamp", "FCB2C01", 
"RCB2C01", "FCB2C02", "RCB2C02", "FCB2C03", "RCB2C03", "FCB2C04", 
"RCB2C04", "FCB2C05", "RCB2C05", "FCB2C06", "RCB2C06", "FCB2C07", 
"RCB2C07", "FCB2C08", "RCB2C08", "FCB2C09", "RCB2C09", "FCB2C10", 
"RCB2C10"), row.names = c(NA, 10L), class = "data.frame") 

和列索引:

idx <- seq(2,21,2) 

回答

4

如果我理解正確,你想要做什麼,「正確」的方法是使用levels函數來指定您的級別。比較以下內容:

set.seed(1) 
x <- sample(-2:4, 10, replace = TRUE) 

YourApproach <- factor(x, levels = -2:4, labels = c(1, 1, 0, 1, 1, 1, 0)) 
# Warning message: 
# In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels, : 
# duplicated levels in factors are deprecated 
YourApproach 
# [1] 1 0 1 0 1 0 0 1 1 1 
# Levels: 1 1 0 1 1 1 0 

xFac <- factor(x, levels = -2:4) 
levels(xFac) <- list(`0` = c(0, 4), `1` = c(-2, -1, 1, 2, 3)) 
xFac 
# [1] 1 0 1 0 1 0 0 1 1 1 
# Levels: 0 1 

請注意每個「級別」的區別。這也意味着底層數字表示將會有所不同:

> as.numeric(YourApproach) 
[1] 2 3 5 7 2 7 7 5 5 1 
> as.numeric(xFac) 
[1] 2 1 2 1 2 1 1 2 2 2 
+0

我試過'水平'與我的數據幀,但它沒有奏效。我用我的數據樣本編輯了我的問題。 – amzu

+0

我不明白爲什麼OP的分組因子水平的方法不起作用。似乎使用「因素」和「標籤」是分組標籤的一種自然方法,而不是聲明因子和重新設置標籤的兩步過程。奇怪。我錯過了一些可能的歧義嗎? – MichaelChirico