r - 如何在 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 列成为第一行。
解决方案
一个选项是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"))
推荐阅读
- node.js - 无法使用解构导入类的静态方法
- scala - 如何在 Scala 中从 Future[Either[Left, Right]] 获取 Future[Right]?
- python - 我正在尝试制作网络抓取工具,但我不断收到此错误
- javascript - 动画儿童旋转面对相机没有给出预期的结果三个js
- image-segmentation - Maskrcnn:误报
- html - CSS `z-index`:使列表项出现在 *previous* 项下方
- python - 使用队列的 Python 程序
- java - 如何在 Kotlin 中获取当前工作目录?
- python - 使用 Open CV 去除背景不精确,部分图片无法正确完成
- arrays - 下拉菜单未反映在 UI 中