2017-08-16 24 views
0

我试图建立一个数据框与我在IMDB上刮过的2个数据:第一个有50个值,第二个只有29个。是否有一个简单的方法来要求R自动填充NA其他21他没有找到的价值?用rvest刮:如何填充一行中的空白数字以在数据框中转换?

我的代码:

imdb <- read_html("http://www.imdb.com/search/title?genres=horror&genres=mystery&sort=moviemeter,asc&view=advanced") 
title <- html_nodes(imdb, '.lister-item-header a') 
title <- html_text(title) 
metascore <- html_nodes(imdb, '.ratings-metascore') 
metascore <- html_text(metascore) 
df <- data.frame(Title = title, Metascore = metascore) 
Error in data.frame(Title = title, Metascore = metascore) : 
    arguments imply differing number of rows: 50, 29 

谢谢!

回答

1

您需要更改第四行。您希望metascore拥有与title一样多的元素,NA对于那些没有列出metascoretitle。执行此操作的方法是提取item-content节点,然后从其中每个节点选择ratings-metascore节点(如果存在),如果不存在,则选择NA。有关html_nodehtml_nodes之间的差异,请参阅?html_nodes。我还添加了span以确保只有数字被返回,而没有以下单词'metascore'。

imdb <- read_html("http://www.imdb.com/search/title?genres=horror&genres=mystery&sort=moviemeter,asc&view=advanced") 
title <- html_nodes(imdb, '.lister-item-header a') 
title <- html_text(title) 
metascore <- html_node(html_nodes(imdb, '.lister-item-content'), '.ratings-metascore span') 
metascore <- html_text(metascore) 
df <- data.frame(Title = title, Metascore = metascore) 

head(df,10) 
       Title Metascore 
1    Mother!  <NA> 
2 Annabelle: Creation 62   
3  Stranger Things  <NA> 
4   Supernatural  <NA> 
5     It  <NA> 
6 The Vampire Diaries  <NA> 
7    Get Out 84   
8  The Originals  <NA> 
9   Annabelle 37   
10    Grimm  <NA>