2015-06-04 165 views
2

我有一个数据帧列表,我需要将每个数据帧中的某个变量转换为因子。更改列表中的R数据帧的变量类型

E.g.

myList <- list(df1 = data.frame(A = sample(10), B = rep(1:2, 10)), 
       df2 = data.frame(A = sample(10), B = rep(1:2, 10)) 
       ) 

可以说变量B需要是每个数据帧中的因子。我试过这个:

TMP <- setNames(lapply(seq_along(myList), function(x) apply(myList[[x]][c("B")], 2, factor)), names(myList)) 

但它只返回转换的变量,而不是我需要的整个数据帧。我知道如何用for循环做到这一点,但我不想诉诸于此。

+2

像'TMP < - lapply(myList中,函数(X){X [, “B”] < - 因子(X [, “B”]); x}); str(TMP)'可能 –

+1

谢谢!这正是我需要的。 – Antti

回答

0

每从大卫Arenburg评论,该解决方案应该工作:

TMP <- lapply(myList, function(x) {x[, "B"] <- factor(x[, "B"]) ; x}) ; str(TMP)