如何将行名称从基于列表的数据框转换为列

时间:2017-04-22 03:32:42

标签: r dataframe dplyr tibble

我有以下基于列表的数据框:


df <- structure(c(5L, 300L, 251L, 42L, 187L, 16L, 2L, 249L, 158L, 17L, 77L, 
  3L, 2L, 166L, 92L, 16L, 86L, 6L, 5L, 104L, 82L, 17L, 37L, 3L, 1L, 248L, 
  239L, 10L, 81L, 2L, 0L, 136L, 107L, 6L, 24L, 3L, 6L, 164L, 147L, 18L, 83L, 
  3L, 1L, 121L, 96L, 1L, 57L, 2L, 0L, 191L, 153L, 15L, 98L, 3L, 5L, 187L, 
  200L, 8L, 83L, 2L, 1L, 289L, 211L, 19L, 113L, 3L, 2L, 169L, 80L, 13L, 48L, 
  1L), .Dim = c(6L, 12L), .Dimnames = list(c("0610005C13Rik", "0610007P14Rik", 
  "0610009B22Rik", "0610009L18Rik", "0610009O20Rik", "0610010B08Rik"), c("control", 
  "control", "control", "control", "control", "control", "treated", "treated", 
  "treated", "treated", "treated", "treated")))

str(df)
#>  int [1:6, 1:12] 5 300 251 42 187 16 2 249 158 17 ...
#>  - attr(*, "dimnames")=List of 2
#>   ..$ : chr [1:6] "0610005C13Rik" "0610007P14Rik" "0610009B22Rik" "0610009L18Rik" ...
#>   ..$ : chr [1:12] "control" "control" "control" "control" ...
df
#>               control control control control control control treated
#> 0610005C13Rik       5       2       2       5       1       0       6
#> 0610007P14Rik     300     249     166     104     248     136     164
#> 0610009B22Rik     251     158      92      82     239     107     147
#> 0610009L18Rik      42      17      16      17      10       6      18
#> 0610009O20Rik     187      77      86      37      81      24      83
#> 0610010B08Rik      16       3       6       3       2       3       3
#>               treated treated treated treated treated
#> 0610005C13Rik       1       0       5       1       2
#> 0610007P14Rik     121     191     187     289     169
#> 0610009B22Rik      96     153     200     211      80
#> 0610009L18Rik       1      15       8      19      13
#> 0610009O20Rik      57      98      83     113      48
#> 0610010B08Rik       2       3       2       3       1

我想要做的是将行名称转换为列我收到此错误:

> df$gene_symbol <- rownames(df)
Warning message:
In df$gene_symbol <- rownames(df) : Coercing LHS to a list

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

首先,正如评论中所指出的,df是一个矩阵而不是数据框。你可以查看:

> class(df)
#[1] "matrix"
> typeof(df)
#[1] "integer"

因此,如您所见,df是一个整数矩阵。请注意,矩阵中的数据只能是相同类型,而在数据框中,您可以存储不同类型的数据。这就是矩阵和数据框架对象的不同之处。

要实现您的目标,您可以将矩阵df转换为数据框,然后执行您想要的操作:

newdf <- data.frame(df)
> class(newdf)
#[1] "data.frame"
newdf$gene_symbol <- rownames(newdf)

完成!