使用dplyr在R中将第一行设置为数据框的列名

13
这是我的数据框:
x<-data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))

colnames(x)<-NULL

我希望能够转置 (t(x)) 并将 x 的第一列作为新数据框 t(x) 的列名。

此外,我需要它们 (t(x) 的列名) 被识别为单词/字母 (字符格式对吧?)

使用 dplyr 包可以实现这个操作吗?

需要帮助吗?

5个回答

13

{清洁工}包非常适合此操作,并且足够灵活,可以选择任何行来推送到列名:


library(tidyverse)
library(janitor)

x <- x %>% row_to_names(row_number = 1)

4
你可以很容易地在基础R中完成这个操作。只需将x的第一列设置为行名,然后删除第一列并转置即可。
row.names(x) = x[,1]
x = t(x[,-1])
x
    a  b  c  d  e  f  g  h  i  j
M1 11 12 13 14 15 16 17 18 19 20
M2 31 32 33 34 35 36 37 38 39 40
M3 41 42 43 44 45 46 47 48 49 50

4

我认为tibble包中的column_to_rownames是最简单的解决方案。在使用t进行转置之前,请先使用它。

library(magrittr)
library(tibble)

x %>% 
  column_to_rownames("A") %>% 
  t

#>     a  b  c  d  e  f  g  h  i  j
#> M1 11 12 13 14 15 16 17 18 19 20
#> M2 31 32 33 34 35 36 37 38 39 40
#> M3 41 42 43 44 45 46 47 48 49 50

上方的"M1"、"M2"、"M3"是行名称。如果你想将它们保留在内部(作为一列),可以从同一软件包中添加rownames_to_column
x %>% 
  column_to_rownames("A") %>% 
  t %>% 
  as.data.frame %>% 
  rownames_to_column("key")

#>   key  a  b  c  d  e  f  g  h  i  j
#> 1  M1 11 12 13 14 15 16 17 18 19 20
#> 2  M2 31 32 33 34 35 36 37 38 39 40
#> 3  M3 41 42 43 44 45 46 47 48 49 50

简而言之,
column_to_rownames("A")x 中的列"A"转换为行名,
t 转置数据框(现在是矩阵),
as.data.frame 重新将其分类为数据框(这对于下一个函数是必要的),并且
rownames_to_column("key") 将行名转换为名为 "key" 的新列。


3

试试这个:

library(dplyr)
library(tidyr)

x <- data.frame(
  A = c(letters[1:10]),
  M1 = c(11:20),
  M2 = c(31:40),
  M3 = c(41:50))

x %>% 
  gather(key = key, value = value, 2:ncol(x)) %>% 
  spread(key = names(x)[1], value = "value")
  key  a  b  c  d  e  f  g  h  i  j
1  M1 11 12 13 14 15 16 17 18 19 20
2  M2 31 32 33 34 35 36 37 38 39 40
3  M3 41 42 43 44 45 46 47 48 49 50

1
使用来自包的rownames_to_column()函数。
library(magrittr)
library(tibble)

x %>%
  t() %>%
  as.data.frame(stringsAsFactors = FALSE) %>%
  rownames_to_column() %>%
  `colnames<-`(.[1,]) %>%
  .[-1,] %>%
  `rownames<-`(NULL)
#>    A  a  b  c  d  e  f  g  h  i  j
#> 1 M1 11 12 13 14 15 16 17 18 19 20
#> 2 M2 31 32 33 34 35 36 37 38 39 40
#> 3 M3 41 42 43 44 45 46 47 48 49 50

x %>% 
  `row.names<-`(.[, 1]) %>% 
  t() %>%
  as.data.frame(stringsAsFactors = FALSE) %>% 
  .[-1,] 
#>     a  b  c  d  e  f  g  h  i  j
#> M1 11 12 13 14 15 16 17 18 19 20
#> M2 31 32 33 34 35 36 37 38 39 40
#> M3 41 42 43 44 45 46 47 48 49 50

reprex包 (v0.2.1.9000)于2018年10月06日创建


我希望在这里使用slice函数来保持它在tidyverse中的整洁性。对于第二个链条,它可以工作,但对于第一个链条则不行。df %>% colnames<-(.[1,]) %>% # 无法将其更改为slice slice(-1) #删除第一行 - PDog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接