我有以下格式的数据。
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")
最佳答案
您可以使用 tidyr
和 dplyr
。
首先我们收集
,使数据变长,而不是变宽。然后我们过滤
只保留项目和动物匹配的那些行:
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/