2017-04-21 38 views
0

内更换因子变量我有dataframes结构的以下列表:不能在列表[R

str(mylist) 

List of 2 
$ L1 :'data.frame': 12471 obs. of 3 variables: 
...$ colA : Date[1:12471], format: "2006-10-10" "2010-06-21" ... 
...$ colB : int [1:12471], 62 42 55 12 78 ... 
...$ colC : Factor w/ 3 levels "type1","type2","type3",..: 1 2 3 2 2 ... 

我想用一个新的因素type4更换type1type2

我曾尝试:

mylist <- lapply(mylist, transform, colC = 
         replace(colC, colC == 'type1','type4')) 
Warning message: 
1: In `[<-.factor`(`*tmp*`, list, value = "type4") : 
    invalid factor level, NA generated 
2: In `[<-.factor`(`*tmp*`, list, value = "type4") : 
    invalid factor level, NA generated 

我不希望在我的stringAsFactor=F初始数据读,但我已经尝试添加type4在我最初的数据集的水平使用(前分裂成dataframes名单) :

levels(mydf$colC) <- c(levels(mydf$colC), "type4") 

但尝试替换时仍然出现相同的错误。

我该如何告诉取代type4是否被视为一个因素?

回答

0

您可以尝试使用levels选项来更新您的因子。 如, status <- factor(status, order=TRUE, levels=c("1", "3", "2",...)) c("1", "3", "2",...)是你的type4在这里。

0

正如您所述,关键的是添加新的因子水平。

## Test data: 
mydf <- data.frame(colC = factor(c("type1", "type2", "type3", "type2", "type2"))) 
mylist <- list(mydf, mydf) 

你的数据有三个因子水平:

> str(mylist) 
List of 2 
$ :'data.frame': 5 obs. of 1 variable: 
    ..$ colC: Factor w/ 3 levels "type1","type2",..: 1 2 3 2 2 
$ :'data.frame': 5 obs. of 1 variable: 
    ..$ colC: Factor w/ 3 levels "type1","type2",..: 1 2 3 2 2 

现在添加第四个因素的水平,那么你的replace命令应该工作:

## Change levels: 
for (ii in seq(along = mylist)) levels(mylist[[ii]]$colC) <- 
    c(levels(mylist[[ii]]$colC), "type4") 

## Replace level: 
mylist <- lapply(mylist, transform, colC = replace(colC, 
    colC == 'type1','type4')) 

新的数据有四个因子水平:

> str(mylist) 
List of 2 
$ :'data.frame': 5 obs. of 1 variable: 
    ..$ colC: Factor w/ 4 levels "type1","type2",..: 4 2 3 2 2 
$ :'data.frame': 5 obs. of 1 variable: 
    ..$ colC: Factor w/ 4 levels "type1","type2",..: 4 2 3 2 2