[英]find out id's of the correlating answers given using r
我有一個包含幾千個條目的數據集。 每個受訪者都標有一個 ID,我想知道回答“調查完成;未發現嫌疑人”的前十名受訪者,因此我創建了一個向量並確定了“調查完成;未發現嫌疑人”的前 10 個條目。
這是我用來創建向量的代碼,它工作得很好。
x<-0
i <- 1
while (x <= 9) {
if (crimes$outcome_status_category[i] %in% "Investigation complete; no suspect identified") {
x <- x+1
no_sus[x] <- crimes$outcome_status_category[i]
}
i <- i +1
}
問題:我試圖找出與“調查完成;未發現嫌疑人”的前 10 個條目相關的受訪者 ID。 我必須使用 if 語句和 while 循環,但我不知道如何做到這一點。 這是我試過的代碼
for( "Investigation complete; no suspect identified" in no_sus){
print (crimes$id)
}
https://imgur.com/Ulc01d7這是我的參考數據集
為什么不只是進行常規子集化,您會得到一個outcome_status_category
,其中所有行都符合您的結果狀態類別標准,然后您可以提取 id 向量。
df <- crimes[crimes$outcome_status_category == "Investigation complete; no suspect identified", ] # extract dataframe with rows that match the criteria
df$id # extract ids
df$id[1:10] # extract first 10 ids
如果您想繼續使用while
並且if
可以將代碼更改為
x<-0
i <- 1
no_id <- numeric(10)
while (x <= 9) {
if (crimes$outcome_status_category[i] %in% "Investigation complete; no suspect identified") {
x <- x+1
no_id[x] <- crimes$id[i]
}
i <- i +1
}
但是,由於大多數情況下您不需要在 R 中顯式使用循環,您也可以這樣做:
result <- head(crimes$id[crimes$outcome_status_category %in% "Investigation complete; no suspect identified"], 10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.