首页 > 解决方案 > 如何创建一个新列,将值与来自不同数据框的标题匹配

问题描述

似乎太简单而不能失败:我有一个包含名称和值的数据框,我想创建一个新列,其中包含解释名称的标签。这些标签存在于单独的数据框中。所以我试图使用dplyr'smutate()pull(),但得到一个错误。

数据

library(tibble)
library(dplyr)

df <-
  tribble(~ animal, ~ weight,
          "dog", 20,
          "cat", 10)

##   animal weight
##   <chr>   <dbl>
## 1 dog        20
## 2 cat        10

我有另一个数据框,其中包含每种动物的标签

labels_tbl <-
  tribble(~ dog, ~ cat,
          "a domesticated carnivore of the family Canidae", "a domestic species of small carnivorous mammal")

##   dog                                            cat                                           
##   <chr>                                          <chr>                                         
## 1 a domesticated carnivore of the family Canidae a domestic species of small carnivorous mammal

而且我知道我可以用来pull()从列中提取值:

pull(.data = labels_tbl, var = dog)

## [1] "a domesticated carnivore of the family Canidae"

所以我试图使用mutateand pull

df %>%
  mutate(label = pull(.data = labels_tbl, var = animal))

但后来得到这个错误:

错误:mutate()输入有问题label。x 必须提取具有单个有效下标的列。x 下标的var大小为 2,但大小必须为 1。

坦率地说,我不明白。

期望的输出

  animal weight label                                         
  <chr>   <dbl> <chr>                                         
1 dog        20 a domesticated carnivore of the family Canidae
2 cat        10 a domestic species of small carnivorous mammal

我会很感激任何解决方案,但我试图弄清楚这种特定方法有什么问题。

标签: rdplyr

解决方案


library(tidyverse)
output <- labels_tbl %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column(var = "animal") %>%
  rename(label = V1) %>%
  right_join(., df, by = "animal")

这使:

  animal                                          label weight
1    dog a domesticated carnivore of the family Canidae     20
2    cat a domestic species of small carnivorous mammal     10

所以我正在做的是转置你的标签查找文件,做一些抛光,然后用你原来的 df 加入 right_join。如果您需要特定的列顺序,您可以多玩一点,但它可以完成工作。


推荐阅读