首页 文章

dplyr包 - 使用mutate将两个或多个函数应用于tbl

提问于
浏览
0

我在SQL中看到这样的数据 .

date_at    price
1 2016-03-02 631USD/1M
2 2016-03-02 741USD/1M
3 2016-03-02 702USD/1M
4 2016-03-02 685USD/1M
5 2016-03-02 738USD/1M
6 2016-03-02 741USD/1M

尝试在R中使用以下代码来获取我想要的表:

df <- tbl(db,"table") %>%
  mutate(newprice = as.numeric(substr(price,1,regexpr("USD",price)-1))) %>%
  select(date, newprice) %>%
  head()

也就是说,我正在尝试将SQL tbl变为跟随,然后选择变量:

date_at    price    newprice
1 2016-03-02 631USD/1M  631 
2 2016-03-02 741USD/1M  741
3 2016-03-02 702USD/1M  702
4 2016-03-02 685USD/1M  685
5 2016-03-02 738USD/1M  738
6 2016-03-02 741USD/1M  741

但是,我无法使用上面的代码创建newprice列 . 得到此错误:

Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  function regexpr("unknown", record) does not exist
HINT:  No function matches the given name and argument types. You may need to add explicit type casts.
)

我发现mutate只能处理一个应用于变量的函数 . 我应该做什么其他功能

1 回答

  • 0

    这可以帮助你:

    df<-data.frame(date_at=c("2016-03-02","2016-03-02","2016-03-02","2016-03-02",
                             "2016-03-02","2016-03-02"),
                   price=c("631USD/1M","741USD/1M","702USD/1M","685USD/1M",
                            "738USD/1M","741USD/1M"))
    
    df%>%
            tbl_df%>%
            mutate(newprice=as.numeric(substr(price,1,regexpr("USD",price)-1)),
                   date_at=as.Date(date_at))%>%
            select(date_at,newprice)%>%
            head()     
    
    Source: local data frame [6 x 2]
    
         date_at newprice
          (date)    (dbl)
    1 2016-03-02      631
    2 2016-03-02      741
    3 2016-03-02      702
    4 2016-03-02      685
    5 2016-03-02      738
    6 2016-03-02      741
    

相关问题