代码之家  ›  专栏  ›  技术社区  ›  eyeOfTheStorm

Spark数据帧的最后一行(使用Sparkyr和dplyr)

  •  1
  • eyeOfTheStorm  · 技术社区  · 8 年前

    想要打印下面数据帧的最后50行,使用类似 tail function 以下按行范围使用Sparkyr,无 arrange collect --我的一些框架很大,没有连续的列。

    library(sparklyr)
    library(dplyr)
    library(Lahman)
    
    spark_install(version = "2.0.0")
    sc <- spark_connect(master = "local")
    
    batting_tbl <- copy_to(sc, Lahman::Batting, "batting"); batting_tbl
    batting_tbl %>% count # Number of rows 
        #   n
        #  <dbl>
        #   1 101332
    
    batting_tbl %>% tail(., n = 50)
    # Error: tail() is not supported by sql sources
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   eyeOfTheStorm    8 年前

    这里有一个解决方案(返回未排序的尾部):

    tbl_df(batting_tbl) %>% slice(101282:101332) # Prints the last 50 rows
    

    下面是第二种解决方案(过滤器索引):

    tbl_df(batting_tbl) %>% arrange(-as.numeric(rownames(.))) %>% head(., n = 50)
    

    **注:以上两项要求 tbl_df 鉴于 batting_tbl %>% head(., n = 50) 不需要收集R数据。并且往往花费更少的时间来计算。感谢@user6910411指出 monotonically_increasing_id() 或者类似的东西将返回火花数据帧而不是R数据。返回的帧 collect() .

    sdf_with_unique_id(batting_tbl, id = "id") %>% arrange(-id) # Id column for sorting