R - 从其他行中提取值

R - Extracting values from other rows

正如标题所暗示的,我想从其他行中提取值。

特别是,作为示例,请考虑以下数据集:

id.in.group <- c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
group <- c(1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4)
trial <- c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3)
subject <- c("s7","s11","s3","s6","s9","s4","s12","s10","s1","s8","s2","s5","s5","s9","s6","s10","s1","s3","s4","s7","s2","s8","s12","s11","s5","s3","s9","s12","s11","s10","s1","s6","s7","s4","s2","s8")

df <- data.frame(group, id.in.group, trial, subject)

df$other1.id <- 0
df$other2.id <- 0

df$other1.id <- ifelse(df$id.in.group == "1" , 2, df$other1.id)
df$other2.id <- ifelse(df$id.in.group == "1" , 3, df$other2.id)

df$other1.id <- ifelse(df$id.in.group == "2" , 1, df$other1.id)
df$other2.id <- ifelse(df$id.in.group == "2" , 3, df$other2.id)

df$other1.id <- ifelse(df$id.in.group == "3" , 1, df$other1.id)
df$other2.id <- ifelse(df$id.in.group == "3" , 2, df$other2.id)

View(df)

鉴于组号 (df$group) 和组中其他人的 ID (df$other1.id 和 df$other2.id),我想创建两个进一步的变量来显示,对于每个试验和每个受试者,其他2个受试者的值而不是他们的相对值id.in.group,从而得到以下两列

df$other1.subject<-c("s11","s7","s7","s9","s6","s6","s10","s12","s12","s2","s8","s8","s9","s5","s5","s1","s10","s10","s7","s4","s4","s12","s8","s8", "s3","s5","s5","s11","s12","s12","s6","s1","s1","s2","s4","s4")
df$other2.subject<-c("s3","s3","s11","s4","s4","s9","s1","s1","s10","s5","s5","s2","s6","s6","s9","s3","s3","s1","s2","s2","s7","s11","s11","s12","s9","s9","s3","s10","s10","s11","s7","s7","s6","s8","s8","s2")

View(df)

例如,如果 trial = 1 且 id.in.group = 1(或者,subject = s7),则 other1.subject = s11 而 other2.subject = s3。我想为每个 id.in.group (或每个主题)或每一行提取这些值。

对不起,如果我没有提供任何先前的尝试,但老实说,我不知道如何解决这个问题。我对任何进一步的澄清持开放态度。

非常感谢您的帮助!

您需要两次离开 join df 与自身 - 一次用于 other1,第二次用于 other2:

library(dplyr)
df %>% 
  left_join(
    df %>% 
      select(group, trial, other1.id = id.in.group, other1.subject = subject),
    by = c("group", "trial", "other1.id")
  ) %>% 
  left_join(
    df %>% 
      select(group, trial, other2.id = id.in.group, other2.subject = subject),
    by = c("group", "trial", "other2.id")
  )