r-sparklyr更改所有列名称spark dataframe


0

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

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

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

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

1 答案

0

您可以使用select_uu with.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

您也可以用选择!!!!:

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

我来回答