需要解决的问题描述:
用户购买物品数据集,每行存储数据格式(user_id,item_id,category_id,ratings,helpfulness,timestamp)
数据事例:
去除那些item_id只出现过一次的行。 问题的规模:922267obs of 2 variables
查找过资料发现如下两个方法:
1.定义一个函数
deleteuniquelines <- function(x) {# x为输入的数据框
stand.col <- x[, 1] # 设根据x的第一列进行删除操作 x[,1]中1为第一列 2为第二列 以此类推
count <- table(stand.col) #table函数可以得到每个上述列每个数所出现的频数
if (all(count < 2)) stop("no repeated records")
else {
ind <- sapply(stand.col, function(t) ifelse(count[as.character(t)] > 1, TRUE, FALSE))
}
return(x[ind, ])
}
test <- data.frame(name = c(1, 1, 2, 3, 3), score = c(2, 2, 3, 2, 4))#测试用例
deleteuniquelines(ratings)
2.使用dplyr包
需要dplyr包
your_datas %>% group_by(#you need to count#) %>% mutate(count=n()) %>% filter(count>1) %>% select(-count)
实例:
ratings %>% group_by(item_id) %>% mutate(count=n()) %>% filter(count>1) %>% select(-count)#将ratings数据集中item_id只出现过一次的行删去
PS: %>%为传递函数的意思 将上一步所得结果传递到下一步
以上两个方法如果规模不大的话,时间差不多,但是在我遇到的问题上,使用第二种方法只需要几秒,而使用第一种方法保守估计得3天
本文介绍如何在R语言中处理数据集,删除那些item_id只出现一次的行。提供了两种方法,包括自定义函数deleteuniquelines和使用dplyr包的解决方案。在大规模数据中,dplyr方法在效率上显著优于自定义函数。
305

被折叠的 条评论
为什么被折叠?



