簡體   English   中英

根據列表中的匹配項重新編碼數據幀變量

[英]Recode a dataframe variable based on matches in a list

我正在嘗試根據與單獨列表中元素的匹配來重新編碼數據框中的變量。 例如:

df <- data.frame(stringsAsFactors = FALSE,
  var1 = c("116", "117", "118", "SL1", "SL2", "234"))

matchList <- list(c("116, 117, and 118", "116", "117", "118"), 
c("SL1/SL2", "SL1", "SL2"))

df
var1
1     116
2     117
3     118
4     SL1
5     SL2
6     234

matchList
[[1]]
[1] "116, 117, and 118" "116"               "117"               "118"              

[[2]]
[1] "SL1/SL2" "SL1"     "SL2"    

如果原始 var1 元素與 matchList 元素的第 2 - 4 項匹配,則應使用相同列表元素的第 1 項對其進行重新編碼。 我希望重新編碼的 var1 如下所示:

var1
1     116, 117, and 118
2     116, 117, and 118
3     116, 117, and 118
4     SL1/SL2
5     SL1/SL2
6     234

以下代碼行一次處理一個列表元素,但我不清楚如何自動執行此操作:

# get indices of matches for matchList element 1
r <- which(df$var1 %in% matchList[[1]]) 
# replace matches with first list item of list element 1 using indices of matches
df$var1[r] <- matchList[[1]][1] 

我已經嘗試了以下 for 循環,但我不確定我錯過了什么

for (i in length(matchList)){
  r <- which(df$var1 %in% matchList[[i]])
  df$var1[r] <- matchList[[i]][1]
}

問題在於length(matchList)是單個值,即 2。相反,我們需要遍歷序列

for(i in seq_along(matchList)) {
     r <- which(df$var1 %in% matchList[[i]])
     df$var1[r] <- matchList[[i]][1]
  } 
df
#               var1
#1 116, 117, and 118
#2 116, 117, and 118
#3 116, 117, and 118
#4           SL1/SL2
#5           SL1/SL2
#6               234

您的方法的替代方法是使用<<-運算符對lapply執行相同的操作。

lapply(matchList, function(x) {
  df$var1[df$var1 %in% x] <<- x[[1]]
})
df

#              var1
#1 116, 117, and 118
#2 116, 117, and 118
#3 116, 117, and 118
#4           SL1/SL2
#5           SL1/SL2
#6               234

但是,在使用<<-之前<<-您可能需要閱讀如何使用范圍分配。

暫無
暫無

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

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