-2

想要将推荐实验室预测列表保存为“”分隔列表的列表。我有一个相同的问题,但在这里想用一个转折来扩展它。

我已经尝试了几种方法,并在下面发现了相关但坚持将输出放入“”逗号分隔脚本的简单步骤。

library("recommenderlab")
library(stringi)
data("MovieLense")
MovieLense100 <- MovieLense[rowCounts(MovieLense) >100,]
MovieLense100
train <- MovieLense100[1:50]
rec <- Recommender(train, method = "UBCF")
rec
pre <- predict(rec, MovieLense100[101:105], n = 10)
as(pre, "list")

list1 = as(pre, "list")

cat(paste0(shQuote(list1[["291"]]),collapse=","))

以上给了我给定的用户:

"Titanic (1997)","Contact (1997)","Alien (1979)","Amadeus (1984)","Godfather, The (1972)","Aliens (1986)","Sting, The (1973)","American Werewolf in London, An (1981)","Schindler's List (1993)","Glory (1989)"

我想将用户和电影放在数据框中,其中第一列将是用户,第二列将是上述连接形式的电影

4

1 回答 1

0

鉴于cat(paste0(shQuote(list1[["291"]]),collapse=","))生成了一串电影推荐,可以执行以下操作将其转换为带有名称标记的数据框:

movies <- cat(paste0(shQuote(list1[["291"]]),collapse=","))
theData <- data.frame(name="Santhosh",movies,stringsAsFactors=FALSE)

另一种方法是将每部电影保存为输出数据框中的单独列,这样可以更轻松地使用 R 中的数据,而无需多次解析电影列表。tidyverse(即tidyrdplyr)可用于生成此数据帧。

library(tidyr)
library(dplyr)
recommendedMovies <- c("Titanic (1997)","Contact (1997)","Alien (1979)","Amadeus (1984)","Godfather, The (1972)","Aliens (1986)","Sting, The (1973)","American Werewolf in London, An (1981)","Schindler's List (1993)","Glory (1989)")
theData <- data.frame(name="Santhosh",
                      rank=1:length(recommendedMovies),
                      movies=recommendedMovies,stringsAsFactors=FALSE)
theData %>% group_by(name) %>%
spread(.,rank,movies,sep="movie")

...和输出:

> theData %>% group_by(name) %>%
+ spread(.,rank,movies,sep="movie")
# A tibble: 1 x 11
# Groups:   name [1]
  name  rankmovie1 rankmovie2 rankmovie3 rankmovie4 rankmovie5 rankmovie6 rankmovie7 rankmovie8 rankmovie9
  <chr> <chr>      <chr>      <chr>      <chr>      <chr>      <chr>      <chr>      <chr>      <chr>     
1 Sant… Titanic (… Contact (… Alien (19… Amadeus (… Godfather… Aliens (1… Sting, Th… American … Schindler…
# ... with 1 more variable: rankmovie10 <chr>
> 
于 2018-12-26T13:22:02.670 回答