r - 数据帧中的二进制操作
问题描述
我有一个关于数据帧中的二进制操作的小问题。在这里我有一个数据框,我想创建一个新列PerWeek
,这是Gross
除以时的结果Weeks
,我想知道我该怎么做,因为Gross
元素不是数字。
boxoffice = function(){
url = "https://www.imdb.com/chart/boxoffice"
read_table = read_html("https://www.imdb.com/chart/boxoffice")
movie_table = html_table(html_nodes(read_table, "table")[[1]])
Name = movie_table[2]
Gross = movie_table[4]
Weeks = movie_table[5]
BoxOffice =
for (i in 1:10){
PerWeek = movie_table[4][i] %/% movie_table[5][i]
}
df = data.frame(Name,BoxOffice,PerWeek)
return(df)
}
解决方案
如果你的Gross
价值总是以百万为单位,你可以从中得到数字并乘以1e6
得到以百万为单位的金额,然后除以Weeks
。
library(rvest)
library(dplyr)
url = "https://www.imdb.com/chart/boxoffice"
read_table = read_html("https://www.imdb.com/chart/boxoffice")
movie_table = html_table(html_nodes(read_table, "table")[[1]])
movie_table <- movie_table[-c(1, ncol(movie_table))]
movie_table %>% mutate(per_week_calc = readr::parse_number(Gross) * 1e6/Weeks)
# Title Weekend Gross Weeks per_week_calc
#1 Onward $10.5M $60.3M 2 30150000
#2 I Still Believe $9.5M $9.5M 1 9500000
#3 Bloodshot $9.3M $10.5M 1 10500000
#4 The Invisible Man $6.0M $64.4M 3 21466667
#5 The Hunt $5.3M $5.8M 1 5800000
#6 Sonic the Hedgehog $2.6M $145.8M 5 29160000
#7 The Way Back $2.4M $13.4M 2 6700000
#8 The Call of the Wild $2.2M $62.1M 4 15525000
#9 Emma. $1.4M $10.0M 4 2500000
#10 Bad Boys for Life $1.1M $204.3M 9 22700000
如果您有数十亿或数千的数据,您可以参考
推荐阅读
- form-submit - html联系表单提交没有响应
- c# - 无法连接到 SQL Server 会话数据库异常 - 所有池连接都在使用中
- django - 通过 Django 在 Cloudinary 中使用可变高度和宽度调整缩略图大小
- django - Django 单元测试:AssertEqual 不将 PermissionDenied 与 403 进行比较,并在 get_object() 中提前终止
- php - Laravel:安排工作或工匠命令?
- c# - 如何从另一个静态类订阅一个类中的事件?
- procmail - procmail - 使用 {} 不会传送到 mbox
- flutter - Flutter/provider——用构造函数初始化一个状态
- powershell - powershell string urldecode 执行时间
- python - 从 Python 数据框中的整数中检索工作日名称