首页 > 解决方案 > 折叠 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

标签: rtidyverse

解决方案


我们可以使用unstackfrom base R(不使用包)

unstack(input, value ~ name)
#   animal  plant
#1    pig   tree
#2    dog   bush
#3    cat flower

dcastdata.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)

推荐阅读