r - 如何创建一个新列,将值与来自不同数据框的标题匹配
问题描述
似乎太简单而不能失败:我有一个包含名称和值的数据框,我想创建一个新列,其中包含解释名称的标签。这些标签存在于单独的数据框中。所以我试图使用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"
所以我试图使用mutate
and 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
我会很感激任何解决方案,但我试图弄清楚这种特定方法有什么问题。
解决方案
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。如果您需要特定的列顺序,您可以多玩一点,但它可以完成工作。
推荐阅读
- oracle - /*+ APPEND_VALUES */ 或 /*+ APPEND*/ ,哪一种对于oracle中的插入操作是有效的
- php - 使用 Material Design Bootstrap 进行 Codeigniter 分页
- python - 计算每个逗号之后的数字以及python中第一个逗号之前的数字
- express - 写入文件后页面未重新加载
- android - 如何检测蓝牙何时完成读取?
- python - 如何修复str对象没有属性'_meta'
- javascript - 如何用动画将一个字母变成另一个字母
- c - 如何从 openssl 库中包含和使用 chacha
- javascript - 使用引导程序在 html 表中浮动文本和图标
- javascript - 调用数字的 toString 方法