Transpose dplyr::tbl object

99封情书 提交于 2019-12-13 17:52:32

问题


I am using src_postgres to connect and dplyr::tbl function to fetch data from redshift database. I have applied some filters and top function to it using the dplyr itself. Now my data looks as below:

   riid   day         hour 
   <dbl> <chr>       <chr>
 1 5542. "THURSDAY " 12   
 2 5862. "FRIDAY   " 15   
 3 5982. "TUESDAY  " 15   
 4 6022. WEDNESDAY   16 

My final output should be as below:
riid    MON   TUES  WED   THUR   FRI   SAT  SUN
5542                       12
5862                             15
5988           15
6022                 16

I have tried spread. It throws the below error because of the class type:

Error in UseMethod("spread_") : no applicable method for 'spread_' applied to an object of class "c('tbl_dbi', 'tbl_sql', 'tbl_lazy', 'tbl')"

Since this is a really big table, I do not want to use dataframe as it takes a longer time. I was able to use as below:

df_mon <- df2 %>% filter(day == 'MONDAY') %>% mutate(MONDAY = hour) %>% select(riid,MONDAY)
df_tue <- df2 %>% filter(day == 'TUESDAY') %>% mutate(TUESDAY = hour) %>% select(riid,TUESDAY)
df_wed <- df2 %>% filter(day == 'WEDNESDAY') %>% mutate(WEDNESDAY = hour) %>% select(riid,WEDNESDAY)
df_thu <- df2 %>% filter(day == 'THURSDAY') %>% mutate(THURSDAY = hour) %>% select(riid,THURSDAY)
df_fri <- df2 %>% filter(day == 'FRIDAY') %>% mutate(FRIDAY = hour) %>% select(riid,FRIDAY)

Is it possible to write all above in one statement?

Any help to transpose this in a faster manner is really appreciated.

EDIT Adding the dput of the tbl object:

structure(list(src = structure(list(con = <S4 object of class structure("PostgreSQLConnection", package = "RPostgreSQL")>, 
    disco = <environment>), .Names = c("con", "disco"), class = c("src_dbi", 
"src_sql", "src")), ops = structure(list(name = "select", x = structure(list(
    name = "filter", x = structure(list(name = "filter", x = structure(list(
        name = "group_by", x = structure(list(x = structure("SELECT riid,day,hour,sum(weightage) AS score FROM\n  (SELECT riid,day,hour,\n  POWER(2,(cast(datediff (seconds,convert_timezone('UTC','PKT',SYSDATE),TO_DATE(TO_CHAR(event_captured_dt,'mm/dd/yyyy hh24:mi:ss'),'mm/dd/yyyy hh24:mi:ss')) as decimal) / cast(7862400 as decimal))) AS weightage\n  FROM (\n  SELECT riid,convert_timezone('GMT','PKT',event_captured_dt) AS EVENT_CAPTURED_DT,\n  TO_CHAR(convert_timezone('GMT','PKT',event_captured_dt),'DAY') AS day,\n  TO_CHAR(convert_timezone('GMT','PKT',event_captured_dt),'HH24') AS hour\n  FROM Zameen_STO_DATA WHERE EVENT_CAPTURED_DT >= TO_DATE((sysdate -30),'yyyy-mm-dd') and LIST_ID = 4282\n  )) group by riid,day,hour", class = c("sql", 
        "character")), vars = c("riid", "day", "hour", "score"
        )), .Names = c("x", "vars"), class = c("op_base_remote", 
        "op_base", "op")), dots = structure(list(riid = riid, 
            day = day), .Names = c("riid", "day")), args = structure(list(
            add = FALSE), .Names = "add")), .Names = c("name", 
    "x", "dots", "args"), class = c("op_group_by", "op_single", 
    "op")), dots = structure(list(~min_rank(desc(~score)) <= 
        1), .Names = ""), args = list()), .Names = c("name", 
    "x", "dots", "args"), class = c("op_filter", "op_single", 
    "op")), dots = structure(list(~row_number() == 1), .Names = ""), 
    args = list()), .Names = c("name", "x", "dots", "args"), class = c("op_filter", 
"op_single", "op")), dots = structure(list(~riid, ~day, ~hour), class = "quosures", .Names = c("", 
"", "")), args = list()), .Names = c("name", "x", "dots", "args"
), class = c("op_select", "op_single", "op"))), .Names = c("src", 
"ops"), class = c("tbl_dbi", "tbl_sql", "tbl_lazy", "tbl"))

回答1:


I think what you're looking for is the ability to run the tidyr::spread() function against a remote source, or database. I have a PR for dbplyr that attempts to implement that here: https://github.com/tidyverse/dbplyr/pull/72, you can try it out by using: devtools::install_github("tidyverse/dbplyr", ref = devtools::github_pull(72)).




回答2:


Use dcast from reshape2 package

> data
# A tibble: 4 x 3
   riid day    hour
  <dbl> <chr> <dbl>
1  1.00 TH     12.0
2  2.00 FR     15.0
3  3.00 TU     15.0
4  4.00 WE     16.0

> dcast(data, riid~day, value.var = "hour")

  riid FR TH TU WE
1    1 NA 12 NA NA
2    2 15 NA NA NA
3    3 NA NA 15 NA
4    4 NA NA NA 16

Further if you want to remove NA, then

> z <- dcast(data, riid~day, value.var = "hour")
> z[is.na(z)] <- ""
> z
  riid FR TH TU WE
1    1    12      
2    2 15         
3    3       15   
4    4          16



回答3:


I tried to combine your multiple line attempts into one. Can you try this and let us know the outcome?

library(dplyr)

df %>%
  rowwise() %>%
  mutate(Mon = ifelse(day=='MONDAY', hour[day=='MONDAY'], NA),
         Tue = ifelse(day=='TUESDAY', hour[day=='TUESDAY'], NA),
         Wed = ifelse(day=='WEDNESDAY', hour[day=='WEDNESDAY'], NA),
         Thu = ifelse(day=='THURSDAY', hour[day=='THURSDAY'], NA),
         Fri = ifelse(day=='FRIDAY', hour[day=='FRIDAY'], NA),
         Sat = ifelse(day=='SATURDAY', hour[day=='SATURDAY'], NA),
         Sun = ifelse(day=='SUNDAY', hour[day=='SUNDAY'], NA)) %>%
  select(-day, -hour)

Output is:

   riid Mon     Tue   Wed   Thu   Fri Sat   Sun  
1  5542 NA       NA    NA    12    NA NA    NA   
2  5862 NA       NA    NA    NA    15 NA    NA   
3  5982 NA       15    NA    NA    NA NA    NA   
4  6022 NA       NA    16    NA    NA NA    NA 

Sample data:

# A tibble: 4 x 3
   riid day        hour
* <dbl> <chr>     <int>
1  5542 THURSDAY     12
2  5862 FRIDAY       15
3  5982 TUESDAY      15
4  6022 WEDNESDAY    16


Update: Can you try below approach using data.table?

library(data.table)

dt <- setDT(df)[, c("Mon","Tue","Wed","Thu","Fri","Sat","Sun") := 
                  list(ifelse(day=='MONDAY', hour[day=='MONDAY'], NA),
                       ifelse(day=='TUESDAY', hour[day=='TUESDAY'], NA),
                       ifelse(day=='WEDNESDAY', hour[day=='WEDNESDAY'], NA),
                       ifelse(day=='THURSDAY', hour[day=='THURSDAY'], NA),
                       ifelse(day=='FRIDAY', hour[day=='FRIDAY'], NA),
                       ifelse(day=='SATURDAY', hour[day=='SATURDAY'], NA),
                       ifelse(day=='SUNDAY', hour[day=='SUNDAY'], NA))][, !c("day","hour"), with=F]


来源:https://stackoverflow.com/questions/50049804/transpose-dplyrtbl-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!