无论如何,从movielens到R studio读取.dat文件

use*_*404 1 r notepad++ rstudio

我试图在R Studio中使用Import Dataset来读取movielens中的ratings.dat.基本上它有这种格式:

 1::1::5::978824268  
 1::1022::5::978300055
 1::1028::5::978301777 
 1::1029::5::978302205 
 1::1035::5::978301753 
Run Code Online (Sandbox Code Playgroud)

所以我需要替换:: by:或'或white space等.我使用notepad ++,它有助于加载文件相当快(比较注意)并且可以轻松查看非常大的文件.但是,当我做替换时,它会显示一些奇怪的字符:

"LF"
Run Code Online (Sandbox Code Playgroud)

正如我在这里做一些研究,它说它是\n(换行或换行).但我不知道为什么当它加载文件时,它不会显示这些,只有当我做替换然后它们出现.当我加载到R Studio时,它仍然检测为"LF",而不是换行并导致数据读取错误.

解决方案是什么?谢谢 !PS:我知道有转换这个的python代码,但我不想使用它,还有其他方法吗?

jlh*_*ard 5

试试这个:

url <- "http://files.grouplens.org/datasets/movielens/ml-10m.zip"

## this part is agonizingly slow
tf <- tempfile()
download.file(url,tf, mode="wb")                          # download archived movielens data
files    <- unzip(tf, exdir=tempdir())                    # unzips and returns a vector of file names
ratings <- readLines(files[grepl("ratings.dat$",files)])  # read rating.dat file
ratings <- gsub("::", "\t", ratings)

# this part is much faster
library(data.table)
ratings <- fread(paste(ratings, collapse="\n"), sep="\t")
# Read 10000054 rows and 4 (of 4) columns from 0.219 GB file in 00:00:07
head(ratings)
#    V1  V2 V3        V4
# 1:  1 122  5 838985046
# 2:  1 185  5 838983525
# 3:  1 231  5 838983392
# 4:  1 292  5 838983421
# 5:  1 316  5 838983392
# 6:  1 329  5 838983392
Run Code Online (Sandbox Code Playgroud)