首页 > 解决方案 > 数据帧中的二进制操作

问题描述

我有一个关于数据帧中的二进制操作的小问题。在这里我有一个数据框,我想创建一个新列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)
}

在此处输入图像描述

标签: rdataframervest

解决方案


如果你的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

如果您有数十亿或数千的数据,您可以参考

将百万/十亿缩写变为实际数字?IE。5.12M -> 5,120,000在 R 中从 K 转换为千 (1000)


推荐阅读