[英]How can I get the index of the rows, from a data.frame with repeated cases, after using the unique() function?
我正在清理我的數據庫“Visitas”,因為它是由每周來醫院一次的患者組成的,所以我重復了很多次相同的主題,而我只是有興趣將患者考慮一次。
我使用unique()
function 來獲取“真實”患者數量,但現在我無法從原始數據庫中獲取它。
我試圖用這些情況創建一個向量,然后使用 which() 來獲取索引,但它不起作用。
我在下面留下一些代碼。
# Visitas_act: active patients who are still going to the hospital
# Visitas_mod: the initial 'Visitas' database but almost cleaned.
# codeep: patient code, identifier
Visitas_mod <- Visitas_mod[Visitas_act, ]
unique(Visitas_mod[, 'codeep'])
Visitas_r <- unique(Visitas_mod[, 'codeep'])
我試過了,但它不起作用,因為索引在“Visitas_mod”數據庫中不匹配
tut <- which(Visitas_mod[, 'codeep'] == Visitas_r)
Visitas_mod <- Visitas_mod[tut, ]
我不完全理解你的問題,但我最好的猜測是這樣的,如果你有任何問題或者我弄錯了,只是評論:)
#create dummy names
names <- cbind(row.names(mtcars),c(1:32))
visit <- sample(names[,1],400,replace = T)
df <- as.data.frame(x = visit)
id <- names[match(df$visit,names),2]
df <- cbind(df,id)
#get vector of unique visitors
uniqV <- unique(df$visit)
#this returns the index of first occurence of a visitor in the dataframe
match(uniqV,df$visit)
Output:
1 2 3 5 6 7 8 9 11 12 13 14 15 20 21 23 24 25 28 30 32 37 46
47 53 58 64 68 85 90 107 120
所有位置都可以用代碼的這個續部分來完成
#return all position of unique visitor in dataset
test <- function(x) {
which(df$visit %in% x)
}
matches <- sapply(uniqV,test)
out <- cbind(as.character(uniqV), unlist(lapply(matches, paste, collapse =",")))
Output:
1 Ford Pantera L 1,98,116,127,128,136,142,189,208,210,217,254,273,275,277,298,313,360
2 Hornet Sportabout 2,19,29,78,81,112,144,234,294,303,322,332,387
3 Merc 280C 3,4,39,159,173,188,308,309,312,351,389
4 Merc 230 5,18,48,77,106,150,161,211,219,240,241,270,299,306,330,365,383
5 Dodge Challenger 6,74,154,172,222,268,336,352,367
6 Valiant 7,26,207,235,258,265,392,397
7 Porsche 914-2 8,45,102,113,117,119,121,131,149,151,224,288,329,343,350,362,394
8 Fiat X1-9 9,10,65,95,135,170,271,282,285,346,380
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.