这是一种使用合并的方法。策略如下。首先将这些对分成p1 和p2(我用tidyr::separate 做了这个)。然后我对跨年份的数据进行子集化,并使用p1 作为唯一标识符进行合并。这意味着现在将有两个不同的p2,一个是 2014 年的,一个是 2015 年的。现在可以直接测试团体是在一起还是离婚。
如果你有很多年,这种方法需要推广。如果需要,我很乐意提供这样的概括。
library(tidyr)
test <-
test %>%
filter(nchar(test$pair) > 3) %>% #getting rid of missing pairs
separate(pair, c("p1", "p2"), "_") %>%
select(-nest) #getting rid of nest which is superfluous
test <- merge(test[test$year=="2014",], test[test$year=="2015",], by = "p1", all = TRUE)
#Same group across 2014 and 2015
na.omit(test[test$p2.x == test$p2.y, grep("p", names(test))])
#Different Group across 2014 and 2015
na.omit(test[test$p2.x != test$p2.y, grep("p", names(test))])
更新
要概括多年的代码,请使用以下代码。这是比循环更好的方法。另请注意,上面的代码不起作用,因为我忘记包含 dplyr 库。请务必下载并加载dplyr 和tidyr。这些库非常适合数据操作。以下是tidyr 和dplyr 的一些来源。如果您还有其他问题,请告诉我。
library(tidyr)
library(dplyr)
test <-
test %>%
filter(nchar(test$pair) > 3) %>% #getting rid of missing pairs
separate(pair, c("p1", "p2"), "_") %>% #splitting pairs
select(-nest) #getting rid of nest which is superfluous
test <- split(test, test$year) #split data into lists by year
test <- Map(function(d, n){names(d)[grepl("p2", names(d))] <- paste("p2", n, sep = "_"); d}, d = test, n = names(test)) #this line can be omitted. It simply insures that your final data set looks nice.
test <- Reduce(function(...) merge(..., by = "p1", all = TRUE), test)
无包(即在 Base R 中)
如果您不想使用 dplyr 和 tidyr 包,您可以用这种基本 R 方法替换前几行代码(直到调用 split)
test <- test[nchar(test$pair) > 3, !names(test)%in%"nest"]
split_pair <- do.call(rbind, strsplit(test$pair, "_"))
test$p1 <- split_pair[, 1]
test$p2 <- split_pair[, 2]
test <- test[, !names(test)%in%"pair"]
最终更新...希望
玩得开心在下面的评论中提出了一个很好的观点。由于我使用p1 作为唯一标识符,因此无法识别p2 何时更改。为了克服这个问题,我做了以下...
test <- split(test, test$year) #split data into lists by year
test <- Reduce(function(...) merge(..., by = c("p1", "p2"), all = TRUE), test) #merge on both p1 and p2 to overcome the previous problem. Pair are now unique identifiers
#Stayed in same relationship
stay = test$year.x == "2014" & test$year.y == "2015"
na.omit(test[stay, ])
#p1 changes couples between year.x and year.y
tp1 <- test[test$p1 %in% test[duplicated(test$p1), "p1"], c("p1", "p2", "year.x", "year.y")]
is_na <- (is.na(tp1$year.x) & is.na(tp1$year.y))
stay_tp1 <- tp1$year.x == "2014" & tp1$year.y == "2015"
stay_tp1[is.na(stay_tp1)] <- FALSE
tp1 <- tp1[!(stay_tp1 | is_na), ]
#A similar approach works for p2. Notice it is probably best to do this in a function. If you do use a function remember you will need to pass your variables as strings, unless you want to use NSE.
最后一段代码可能有点混乱。让我解释。为了确定一只鸟是否改变了伙伴,我们识别重复,因为从一对移动到另一对的鸟会出现两次。然而,在多年的情况下,鸟类可以在几年中的任何一年改变对。要识别鸟改变的正确年份,您需要使用上面的代码。我建议你构造一个函数来处理这种情况,因为这涉及到相当多的打字。