创建具有一行和多列的数据框

时间:2019-06-07 19:05:18

标签: r dataframe

我将创建一个包含12列和一行的数据框。 我有此数据:

Tissues <-
 [1] "ova"                      "testes"                   "optic_lobe"               "retina"                   "suckers"                 
 [6] "subesophageal_brain"      "Supraesophageal_brain"    "skin"                     "stage15tissues"           "axial_nerve_corde"       
[11] "posterior_salivary_gland" "viscera"                 
 reads <-
 [1] 22444744 30671024 22648756 24002307 26438055 48999389 60168243 30172728 26812536 23359754 24038817 25570689

我要创建这个:

       tissue1 tissue2 tissue3 tissue4 tissue5 tissue6 etc..
reads       1       2       3        4      5        6  

我尝试过:

df <- data.frame(matrix(ncol = 12, nrow = 1))
x <- TESSUTI
colnames(df) <- x

但是如何将读取的数据添加到每一列?

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

有一个可复制的示例很有帮助,我们可以轻松地复制和粘贴

这是一个解决方案:

##Your input data
tissues <- letters[1:12]
reads <- rnorm(n = 12,mean = 250000,sd = 1000)

##Put the reads into one row of a matrix, then convert to dataframe
data <- data.frame(matrix(nrow = 1,data = reads))

##set the colnames to match your tissue, and the reads row to have a reads name
colnames(data) <- tissues
rownames(data) <- 'reads'

print(data)
           a      b      c      d      e      f      g      h      i      j      k      l
reads 250813 250376 250178 251138 251033 249945 250165 248150 251168 251193 249658 250621

答案 1 :(得分:1)

您可以创建一个具有两个矢量的数据框,并使用spread()中的tidyr散布成一个列

library(tidyr)

# data
Tissues <- c( "ova", "testes", "optic_lobe", "retina", "suckers",
   "subesophageal_brain","Supraesophageal_brain","skin",
   "stage15tissues", "axial_nerve_corde", "posterior_salivary_gland", "viscera")                 

reads <-c(22444744, 30671024, 22648756, 24002307, 26438055, 48999389,
          60168243, 30172728, 26812536, 23359754, 24038817, 25570689)


df <- *emphasized text*data.frame(Tissues, reads) %>%
  spread(Tissues, reads)

答案 2 :(得分:0)

df <- setNames(data.frame(t(c(22444744, 30671024, 22648756, 24002307, 26438055, 48999389, 60168243, 30172728, 26812536, 23359754, 24038817, 25570689))),
         c("ova", "testes", "optic_lobe", "retina","suckers" , "subesophageal_brain", "Supraesophageal_brain",
           "skin", "stage15tissues", "axial_nerve_corde", "posterior_salivary_gland","viscera"))
rownames(df) <- "read"
df

其中大多数都在1行中,结果是:

          ova   testes optic_lobe   retina  suckers subesophageal_brain Supraesophageal_brain     skin stage15tissues axial_nerve_corde posterior_salivary_gland  viscera
read 22444744 30671024   22648756 24002307 26438055            48999389              60168243 30172728       26812536          23359754                 24038817 25570689