r - 数据整理 - 将一列中的值与其他列中的值匹配

标签 r

我有以下格式的数据。

Noun   InCage   InHouse   InGarage   InTree
Bird   Bird     Dog       None       Cat
Cat    Bird     Dog       None       Cat
Dog    Bird     Dog       None       Cat

我想要这种格式:

Noun    Place
Bird    InCage
Cat     InTree
Dog     InHouse

除了编写一堆 if 语句之外,还有什么更聪明的方法可以做到这一点?

这是我提到的小例子的输出。

structure(list(
    Item = structure(c(2L, 3L, 1L), .Label = c("Bird", "Cat", 
    "Dog"), class = "factor"), InTree = structure(c(1L, 1L, 1L
    ), .Label = "Cat", class = "factor"), InHouse = structure(c(1L, 
    1L, 1L), .Label = "Dog", class = "factor"), InCage = structure(c(1L, 
    1L, 1L), .Label = "Bird", class = "factor"), InGarage = structure(c(1L, 
    1L, 1L), .Label = "none", class = "factor")), .Names = c("Item", "InTree", 
    "InHouse", "InCage", "InGarage"
    ), row.names = c(NA, -3L), class = "data.frame")

最佳答案

您可以使用 tidyrdplyr

首先我们收集,使数据变长,而不是变宽。然后我们过滤只保留项目和动物匹配的那些行:

library(tidyr)
library(dplyr)
dat %>% gather(place, animal, -Item) %>%
        filter(as.character(Item) == as.character(animal))

  Item   place animal
1  Cat  InTree    Cat
2  Dog InHouse    Dog
3 Bird  InCage   Bird

关于r - 数据整理 - 将一列中的值与其他列中的值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34122223/

相关文章:

r - 根据两列中的值在 R 中创建新列

r - 读取 json 文件时将嵌套列表转换为数据帧

r - 如何使用 R 动态地将值插入数据框中

r - 将 R 输出导出到 TXT 文件时如何修复损坏的格式?

r - 如何在 ggplot2 中按时间顺序排列月份而不是写出月份?

r - Summarise_each 为第一个非 NA 值

在 R 中添加时删除 NA

r - R引用类中有析构函数吗?

r - 我可以在 r 传单 "map_shape_click"事件中使用数据表填充 box() 吗?

r - 如何将列表翻过来?