将字符数组写入表

时间:2014-08-26 00:06:04

标签: r transpose sapply

我想转置最后一个命令给出的输出并将其写入data.frame。我希望该数据帧有2列。第一列将具有列名称,第二列将具有每行中列的数据类型。我怎么能实现它?我尝试了各种各样的东西,但没有得到我想要的东西

smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
smoke <- as.data.frame(smoke)
table1=sapply (smoke, class)
table1

4 个答案:

答案 0 :(得分:4)

您也可以跳过table1部分,直接从smoke转到所需的结果。

> data.frame(nm = names(smoke), cl = sapply(unname(smoke), class))
#   nm      cl
# 1 V1 numeric
# 2 V2 numeric
# 3 V3 numeric

答案 1 :(得分:3)

你可以试试这个:

data.frame(var.name = names(table1), var.class = table1, row.names=NULL)
#  var.name var.class
#1       V1   numeric
#2       V2   numeric
#3       V3   numeric

答案 2 :(得分:2)

您可能正在寻找melt命令。

library(reshape2)

smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
smoke <- as.data.frame(smoke)
table1 <- sapply (smoke, class)
smoke.melt <- melt(smoke)

levels(smoke.melt$variable) <- table1

> smoke.melt
  variable value
1  numeric    51
2  numeric    92
3  numeric    68
4  numeric    43
5  numeric    28
6  numeric    22
7  numeric    22
8  numeric    21
9  numeric     9

答案 3 :(得分:1)

只需将table1转换为data.frame并调整:

dd = data.frame(table1)
dd
    table1
V1 numeric
V2 numeric
V3 numeric

dd$VarName = rownames(dd)
dd
    table1 VarName
V1 numeric      V1
V2 numeric      V2
V3 numeric      V3

dd = dd[,c(2,1)]
dd
   VarName  table1
V1      V1 numeric
V2      V2 numeric
V3      V3 numeric

names(dd)[2] = "type"
dd
   VarName    type
V1      V1 numeric
V2      V2 numeric
V3      V3 numeric