我有以下数据结构:团体中的人员会议。小组见面的频率不同,每次聚会的小组成员人数也各不相同。
$ GroupID : chr "1" "1" "1" "1" ...
$ groupnames : chr "A&M" "A&M" "A&M" "A&M" ...
$ MeetiID : chr "1" "1" "2" "2" ...
$ Date_Meetings : chr "43293" "43293" "43298" "43298" ...
$ PersonID : num 171 185 171 185 185 113 135 113 135 113 ...
$ v_165 : chr "3" "3" "4" "3" ...
$ v_166 : chr "2" "2" "3" "3" ...
$ v_167 : chr "2" "4" "4" "3" ...
$ v_168 : chr "6" "7" "4" "5" ...
$ problemtypes_categories: chr "Knowledgeproblem" "Knowledgeproblem" "Motivationalproblem" "Coordinationproblem" ...
$ v_165_dicho : num 0 0 0 0 1 1 1 0 0 1 ...
$ v_166_dicho : num 0 0 0 0 0 0 0 0 0 0 ...
$ v_167_dicho : num 0 0 0 0 1 1 0 0 0 0 ...
现在我必须创建一个新变量,它应该是二进制 (0/1),名称为 agreement_levels。因此,每次,在同一个学习会议上,一个小组中的一个人与同一小组的其他学习者在同一会议上拥有相同的问题类型类别,两个学习者(或三个或四个,取决于各个会议的组大小)应该在协议变量中获得值 1,否则他们都应该获得 0。每当一个人(例如,在四个学习者中)已经有与其他人不同的问题类别时,在所有人的协议变量。如果同一会议的数据集中只有 1 个人,则必须有一个 NA 表示同意。然而,当一个人在问题类型变量上有 NA 时,并且在同一会议的数据集中有 2 个人,两者在同意时都为 0;
我已经写了一个命令,但它还没有工作,仍然不考虑 NAs:
GroupID1 <- df$GroupID[1:nrow,]
TreffID1 <- df$TreffID[1:nrow,]
for(i in 1:(GroupID1 -1){
for(j in 1:(TreffID1 -1){
if(df[i, 3] == df[i+1, 3]-1){
if(df[i, 15] == df[i+1, 15]-1){
df[c(i, i+1), 28] <- 1,
df[c(i, i+1), 28] <- 0
提前谢谢了。
dput(head(df))
structure(list(GroupID = c("1", "1", "1", "1", "1", "2"), TreffID = c("1", "1",
"2", "2", "3", "1"), PersonID = c(171, 185, 171, 185,
185, 113), problemtypen_oberkategorien = c("Verständnisprobleme",
"Verständnisprobleme", "Motivationsprobleme", "Motivationsprobleme",
"Motivationsprobleme", "Motivationsprobleme"), passung.exkl = c("0",
"0", "0", "0", "1", "1")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
我使用 R's 代替循环dplyr
。我不确定我的逻辑是否正确,因为那里有很多。例如,您没有指定 NA 问题类型和 3 个人会发生什么。但这里是一个使用 的起点group_by
,因此您正在查看具有相同 GroupID 和 TreffID 的每组行,然后mutate
和case_when
,根据条件将值分配给新列,然后像n()
这样计算行数并且n_distinct
计算不同的行,所以如果它是 ==1 那么我们知道它们都是相同的。
library(tidyverse)
df <- df %>%
group_by(GroupID, TreffID) %>%
mutate(agreement_levels = case_when(n() == 1 ~ -1,
is.na(problemtypen_oberkategorien) & n() == 2 ~ 0,
is.na(problemtypen_oberkategorien) & n() > 2 ~ -1,
n_distinct(problemtypen_oberkategorien, na.rm = FALSE) == 1 ~ 1,
n_distinct(problemtypen_oberkategorien, na.rm = FALSE) > 1 ~ 0,
TRUE ~ -1),
agreement_levels = na_if(agreement_levels, -1)) %>%
select(GroupID, TreffID, problemtypen_oberkategorien, agreement_levels, everything())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句