我有以下代码
fig4 <- data.frame(chads=NA,age=NA,treatment=NA,mean=NA,lower=NA,upper=NA)
fig4$chads <- as.factor(fig4$chads)
levels(fig4$chads) <- c(0,1,2,3,4,5,6)
fig4$age <- as.factor(fig4$age)
levels(fig4$age ) <- c("u80","o80")
fig4$treatment <- as.factor(fig4$treatment)
levels(fig4$treatment) <- c("OAC","OAP")
fig4$mean <- as.numeric(fig4$mean)
fig4$lower <- as.numeric(fig4$lower)
fig4$upper <- as.numeric(fig4$upper)
> str(fig4)
'data.frame': 1 obs. of 6 variables:
$ chads : Factor w/ 7 levels "0","1","2","3",..: NA
$ age : Factor w/ 2 levels "u80","o80": NA
$ treatment: Factor w/ 2 levels "OAC","OAP": NA
$ mean : num NA
$ lower : num NA
$ upper : num NA
到目前为止一切顺利。但后来我这样做了:
vc <- as.vector(c(6,"o80","OAC",0.1,0.02,0.25), mode = "any")
fig4 <- rbind(fig4,vc)
结果如下:
> str(fig4)
'data.frame': 2 obs. of 6 variables:
$ chads : Factor w/ 7 levels "0","1","2","3",..: NA 7
$ age : Factor w/ 2 levels "u80","o80": NA 2
$ treatment: Factor w/ 2 levels "OAC","OAP": NA 1
$ mean : chr NA "0.1"
$ lower : chr NA "0.02"
$ upper : chr NA "0.25"
为什么数字向量变成字符向量?
答案 0 :(得分:3)
列表可以容纳多种类型的对象,因此为了避免将新数据转换为字符,您可以执行以下操作:
fig4[nrow(fig4) + 1, ] <- list(6,"o80","OAC",0.1,0.02,0.25)
答案 1 :(得分:2)
出于同样的原因,矩阵将 - 矢量和矩阵都只能容纳一个类型。当你强迫角色进入混音时,你会得到角色。
使用data.frame保存不同类型的“列”,然后对各列进行子集。