转换为char后data.frame中的列属性。矩阵(转置)。

时间:2014-01-09 04:18:35

标签: r dataframe

我想知道我是否可以在不将“因素”指定为属性的情况下读取data.frame(下面的“a”)。我想将字符/字符串作为因子和数字作为数字(不必调用每一列)。

x <- matrix(letters[1:9],3)
x<-rbind(x,c(0,2,2))
rownames(x) <- c('c1','c2','c3','c4')
y <- data.frame(x)
z <- t(y)
a <- data.frame(z)      
str(a)

1 个答案:

答案 0 :(得分:0)

每次创建data.frame时都添加条件stringsAsFactors=FALSE

y <- data.frame(x,stringsAsFactors=FALSE)

a <- data.frame(z,stringsAsFactors=FALSE) 

将后面的4列更改为数字:

> a[,4]=as.numeric(a[,4])

> a
   c1 c2 c3 c4
X1  a  b  c  0
X2  d  e  f  2
X3  g  h  i  2

> str(a)
'data.frame':   3 obs. of  4 variables:
 $ c1: chr  "a" "d" "g"
 $ c2: chr  "b" "e" "h"
 $ c3: chr  "c" "f" "i"
 $ c4: num  0 2 2