r - 折叠 2-col 数据框,其中 col1 包含名称,col2 包含值
问题描述
我认为必须有一种简单的方法来折叠输入表以产生所需的输出表,但我对此一无所知。
library(tidyverse)
input <- tribble(
~name, ~value,
"animal", "pig",
"animal", "dog",
"animal", "cat",
"plant", "tree",
"plant", "bush",
"plant", "flower"
)
output <- tribble(
~animal, ~plant,
"pig", "tree",
"dog", "bush",
"cat", "flower"
)
在input
中,col1 包含 col2 中每个值的变量标签。在output
中,表格被重新格式化,以便 中的值input$value
出现在根据 中的相应元素命名的列中input$name
。
解决方案
我们可以使用unstack
from base R
(不使用包)
unstack(input, value ~ name)
# animal plant
#1 pig tree
#2 dog bush
#3 cat flower
或dcast
从data.table
library(data.table)
dcast(input, rowid(name)~ name)[,-1]
# animal plant
#1 pig tree
#2 dog bush
#3 cat flower
或使用dplyr
library(dplyr)
input %>%
group_split(name, keep = FALSE) %>%
bind_cols
或使用split
split(input$value, input$name) %>%
bind_cols
或另一种选择spread
library(tidyr)
input %>%
mutate(rn = rowid(name)) %>%
spread(name, value)
推荐阅读
- docker - Kubernetes 不能为私有 Docker 存储库使用秘密
- javascript - 如何在反应路由器组件中传递道具?
- actions-on-google - Google Action Console:不接受隐私权政策
- c++ - 如何确定 CRC16 初始校验和,因此生成的校验和为零
- php - 条纹@缺少参数 success_url ,即使它存在
- java - 截取屏幕截图并发送,而不保存在移动设备内存中
- java - 代码不在 IntelliJ 上运行,但在 NetBeans 上运行
- python - Pandas - 在 Dataframe 子图中重复 vline
- c++ - 重载 istream 运算符以在多行项目中显示分数
- python - Python:模块'pyarrow'没有属性'orc'