让我说我创建了这样的数据表:
a = c(1,2,3,4,2,2,5,3,1)
b = c(4,5,2,2,1,1,1,1,3)
c = c(1,1,1,0,0,0,0,0,1)
abc = rbind(a,b,c)
abc = as.data.frame(t(abc))
str(abc)
,最后一行将返回以下数据表:
'data.frame': 9 obs. of 3 variables:
$ a: num 1 2 3 4 2 2 5 3 1
$ b: num 4 5 2 2 1 1 1 1 3
$ c: num 1 1 1 0 0 0 0 0 1
我想转换列a& b成因素:
abc[,c("a","b")] = apply(abc[, c("a","b")], 2, factor)
但由于某种原因,它只是没有变成因素而是字符:
'data.frame': 9 obs. of 3 variables:
$ a: chr "1" "2" "3" "4" ...
$ b: chr "4" "5" "2" "2" ...
$ c: num 1 1 1 0 0 0 0 0 1
但如果我单独做的话:
abc[,'c'] = as.factor(abc[,'c'])
它会起作用:
> str(abc)
'data.frame': 9 obs. of 3 variables:
$ a: chr "1" "2" "3" "4" ...
$ b: chr "4" "5" "2" "2" ...
$ c: Factor w/ 2 levels "0","1": 2 2 2 1 1 1 1 1 2
为什么会这样?为什么我不能将这些数字转换成因素? 任何帮助表示赞赏