Can anyone suggest a faster way to iterate or loop over this data frame?
I have a dataframe with approximately 500,000 rows and four columns. The dataframe contains data about visits to a location by a specific user. A sample of the dataframe is is below:
> head(data)
FirstVisit VisitDate ID visit.count
1 40545 40545 000001 1
2 40545 40545 000002 1
3 40548 40548 000003 1
4 40545 40565 000001 2
5 40545 40575 000002 2
6 40545 40576 000002 3
Each observation contains a user's first date (in integer format where 1 is 01/01/1900), their visit date, their unique ID (there are approximately 175,000 unique IDs), and the visit count (is it their first visit, second visit, etc.?). Visits are capped at five, so the maximum value in the visit.count column is less than or equal to five. I would like to create a matrix (or dataframe, if necessary) that stores the most recent visit count for each ID; something like:
> head(data.matrix)
ID visit.count1 visit.count2 visit.count3 visit.count4 visit.count5
1 000001 0 1 0 0 0
2 000002 0 0 1 0 0
3 000003 1 0 0 0 0
My code is below:
ids <- unique(data$ID)
count.matrix <- matrix(data = 0, nrow = length(ids), ncol = 5)
for (i in 1:length(ids)){
ss <- subset(x = data, subset = data$ID==ids[i])
ifelse(
length(rownames(ss))==5,
count.matrix[i,5] <- 1,
ifelse(
length(rownames(ss))==4,
count.matrix[i,4] <- 1,
ifelse(
开发者_JS百科 length(rownames(ss))==3,
count.matrix[i,3] <- 1,
ifelse(
length(rownames(ss))==2,
count.matrix[i,2] <- 1,
count.matrix[i,1] <- 1
)
)
)
)
}
How can I improve upon this?
If you don't need separate columns,
tapply(data$visit.ccount, data$ID, max)
should get you a long way. If you do, you can use it to base the 'columnised version' on it.
You could use table
function
tb <- table(data$ID)
data.matrix <- data.frame(
ID = names(tb),
visit.count1 = as.numeric(tb==1),
visit.count2 = as.numeric(tb==2),
visit.count3 = as.numeric(tb==3),
visit.count4 = as.numeric(tb==4),
visit.count5 = as.numeric(tb==5)
)
If you sort by the vist count and then remove the duplicates (lower visit counts):
data2 <- data[order(data$visit.count,decreasing=T),]
data2 <- data2[!duplicated(data2$ID),]
精彩评论