首页 > 解决方案 > 如何在 R 中将 2 列转换为 2 行?

问题描述

我有一个 2 列数据框,我想变成 2 行。维度是 40 个观察值和 2 个变量(而我想要的是 40 个变量和 1 个观察值,因为我希望第一行成为列标题)。

我尝试过使用 reshape,但我似乎无法正确使用它,因为我不断收到错误。这是我正在使用的数据框:

      Data.Label                      Test2
1     Family                          Petromyzontidae - lampreys
2     Species                         Ichthyomyzon castaneus
3     Taxonomic Authority             Girard, 1858
4     Common Name(s)                  Chestnut Lamprey
5     French Name                     lamproie brune
6     OMNR Code                       016
Test5 <- reshape(Test4, timevar = Test4$Data.Label, idvar = Test4$Test2,direction = "wide")
Error in `[.data.frame`(data, , idvar) : undefined columns selected

如前所述,我尝试使用重塑。因为有 40 个变量我想成为列标题 (Test4$Data.Label),所以我不想为 idvars 写出每一个变量。还有另一种方法可以做到这一点吗?

期望的结果是:

Family                     Species                Taxonomic Authority                Common Name(s)                French Name                OMNR Code                      
Petromyzontidae lampreys   Ichthyomyzon castaneus  Girard, 1858                      Chestnut Lamprey             lamproie brune              016

这样,Test4$Data.Label 列成为列标题(总共 40 个),Test4$Test2 列成为第一行。

标签: r

解决方案


一个选项是deframe转换为list

library(tidyverse)
deframe(df1) %>%
      as.list %>% 
      as_tibble
# A tibble: 1 x 6
#  Family                   Species              `Taxonomic Authorit… `Common Name(s)` `French Name` `OMNR Code`
#  <chr>                    <chr>                <chr>                <chr>            <chr>         <chr>      
#1 Petromyzontidae - lampr… Ichthyomyzon castan… Girard, 1858         Chestnut Lamprey lamproie bru… 016      

数据

df1 <- structure(list(Data.Label = c("Family", "Species",
"Taxonomic Authority", 
"Common Name(s)", "French Name", "OMNR Code"), 
 Test2 = c("Petromyzontidae - lampreys", 
"Ichthyomyzon castaneus", "Girard, 1858", "Chestnut Lamprey", 
"lamproie brune", "016")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

推荐阅读