gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:23:58 25 4
gpt4 key购买 nike

我有以下格式的数据。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com