[英]Looping through a dataset, comparing values to another dataset
我有兩個數據集。 One(DFlogin) 包含一組用戶 ID,以及他們試圖從中登錄的兩位數字“郵政編碼”。 另一個(Dfrecords)包含一個可接受的“郵政編碼”列表,供用戶登錄。
對於用戶,他們可以嘗試登錄任意數量的郵政編碼,以及任意數量的可接受的記錄郵政編碼。
目標是遍歷 DFlogin 數據集的行,並將每個用戶嘗試登錄的次數與特定用戶的所有可接受的登錄次數進行比較。
因此,用戶 1 只能在郵政編碼 34 中登錄,但已從郵政編碼 21 登錄。該用戶應在新列 (bad_login) 中進行標記。
userid<-c(1:3)
zipcode1<-c(21,23,4)
zipcode2<-c(NA, 34, 32)
DFlogin<-data.frame(userid,zipcode1,zipcode2)
recordzipcode1<-c(34,23,42)
recordzipcode2<-c(NA, 34, 32)
recordzipcode3<-c(NA, 21,61)
DFrecords<-data.frame(userid, recordzipcode1,recordzipcode2, recordzipcode3)
我想該解決方案可以使用幾個循環和一個 if 語句,但我不確定從哪里開始。
您可以在DFlogin
上DFlogin
行apply
。
在DFrecords
表中查找匹配的ID
。 僅選擇具有郵政編碼值 ( 2:4
) 的列。 刪除NA
值。 檢查所有值(即登錄名)是否來自可接受的郵政編碼。
DFlogin$bad_login <- apply(DFlogin, 1, function(x) {
x1 = DFrecords[match(x[1], DFrecords$userid),2:4]
#2:4 are the columns having zipcodes in DFrecords
y = x1[!is.na(x1)]
as.integer(!all(x[2:3] %in% y))
#2:3 are the columns having zipcodes in DFlogin
})
#[1] 1 0 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.