【问题标题】:sparklyr change all column names spark dataframesparklyr 更改所有列名 spark 数据框
【发布时间】:2018-01-19 04:59:04
【问题描述】:

我打算更改所有列名。当前的重命名或选择操作太费力了。我不知道是否有人有更好的解决方案。如下示例:

df <- data.frame(oldname1 = LETTERS, oldname2 = 1,...oldname200 = "APPLE")
df_tbl <- copy_to(sc,df,"df")
newnamelist <- paste("Name", 1:200, sep ="_")

如何将 newnamelist 指定为新的列名?我可能做不到:

df_new <- df_tbl %>% dplyr::select(Name_1 = oldname1, Name_2 = oldname2,....)

【问题讨论】:

  • 这有帮助吗? names(df)[1:3] &lt;- sprintf("NEW_COLUMN%d", 1:3)您可以通过更改上述语句中的数字来添加“n”列。

标签: r apache-spark dataframe dplyr sparklyr


【解决方案1】:

您可以将select_.dots 一起使用:

df <- copy_to(sc, iris)

newnames <- paste("Name", 1:5, sep="_")

df %>% select_(.dots=setNames(colnames(df), newnames))
# Source:   lazy query [?? x 5]
# Database: spark_connection
   Name_1 Name_2 Name_3 Name_4 Name_5
    <dbl>  <dbl>  <dbl>  <dbl>  <chr>
 1    5.1    3.5    1.4    0.2 setosa
 2    4.9    3.0    1.4    0.2 setosa
 3    4.7    3.2    1.3    0.2 setosa
 4    4.6    3.1    1.5    0.2 setosa
 5    5.0    3.6    1.4    0.2 setosa
 6    5.4    3.9    1.7    0.4 setosa
 7    4.6    3.4    1.4    0.3 setosa
 8    5.0    3.4    1.5    0.2 setosa
 9    4.4    2.9    1.4    0.2 setosa
10    4.9    3.1    1.5    0.1 setosa

你也可以select!!!:

library(rlang)
library(purrr)

df %>% select(!!! setNames(map(colnames(df), parse_quosure), newnames))
# Source:   lazy query [?? x 5]
# Database: spark_connection
   Name_1 Name_2 Name_3 Name_4 Name_5
    <dbl>  <dbl>  <dbl>  <dbl>  <chr>
 1    5.1    3.5    1.4    0.2 setosa
 2    4.9    3.0    1.4    0.2 setosa
 3    4.7    3.2    1.3    0.2 setosa
 4    4.6    3.1    1.5    0.2 setosa
 5    5.0    3.6    1.4    0.2 setosa
 6    5.4    3.9    1.7    0.4 setosa
 7    4.6    3.4    1.4    0.3 setosa
 8    5.0    3.4    1.5    0.2 setosa
 9    4.4    2.9    1.4    0.2 setosa
10    4.9    3.1    1.5    0.1 setosa
# ... with more rows

【讨论】:

    【解决方案2】:

    上面列出的解决方案对我不起作用。我确实在 github 中找到了一个与 sparklyr 一起使用的直接解决方案。

    rename() doesn't support unquoting of character vectors #3030

    下面是我的脚本的摘录,它扩展了上面链接中描述的方法。

    library(dplyr)
    library(stringr)
    
    # Generate list of column names without special characters (replace spaces and dashes with underscores)
    list_new_names = colnames(spark_df) %>% str_remove_all('LAST ') %>% str_replace_all(' - ', '_') %>% str_replace_all(' ', '_')
    # Generate list used to rename columns
    list_new_names = colnames(spark_df) %>% setNames(list_new_names)
    # Rename columns
    spark_df = spark_df %>% rename(!!! list_new_names)
    

    【讨论】:

      【解决方案3】:

      你也可以这样做,这对我来说很好。

      df <- copy_to(sc, iris)
      newnames <- paste("Name", 1:5, sep="_")
      
      colnames(df) <- newnames
      

      【讨论】:

        猜你喜欢
        • 2018-01-12
        • 2020-04-28
        • 2019-12-02
        • 2018-01-16
        • 2011-08-30
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        相关资源
        最近更新 更多