簡體   English   中英

與其他data.frame中的行匹配的列表列元素

[英]elements of list column matching rows in other data.frame

我有以下兩個data.frames:

df1 <- data.frame(Var1=c(3,4,8,9),
               Var2=c(11,32,1,7))

> df1
  Var1 Var2
1    3   11
2    4   32
3    8    1
4    9    7

df2 <- data.frame(ID=c('A', 'B', 'C'),
                ball=I(list(c("3","11", "12"), c("4","1"), c("9","32"))))

> df2
  ID      ball
1  A 3, 11, 12
2  B      4, 1
3  C     9, 32

請注意, df2中的列ball是一個列表。

我想在df2選擇ID ,其中列ball中的元素與df1中的一行匹配。

理想的輸出如下所示:

> df3
  ID ball1 ball2
1  A     3    11

有誰知道如何有效地做到這一點? 原始數據在兩個data.frames中都包含數百萬行。

data.table解決方案比該基礎R解決方案的運行速度要快得多,但這是有可能的。

您的數據:

df1 <- data.frame(Var1=c(3,4,8,9),
                  Var2=c(11,32,1,7))
df2 <- data.frame(ID=c('A', 'B', 'C'),
                  ball=I(list(c("3","11", "12"), c("4","1"), c("9","32"))))

過程:

df2$ID <- as.character(df2$ID) # just in case they are levels instead

n <- length(df2)# initialize the size of df3 to be big enough
df3 <- data.frame(ID = character(n),
                  Var1 = numeric(n), Var2 = numeric(n), 
                  stringsAsFactors = F) # to make sure we get the ID as a string
count = 0 # counter
for(i in 1:nrow(df1)){
  for(j in 1:nrow(df2)){
    if(all(df1[i,] %in% df2$ball[[j]])){
      count = count + 1
      df3$ID[count] <- df2$ID[j]
      df3$Var1[count] <- df1$Var1[i]
      df3$Var2[count] <- df1$Var2[i]
    }
  }
}
df3_final <- df3[-which(df3$ID == ""),] # since we overestimated the size of d3
df3_final

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM