首页 > 解决方案 > 将列移动到第三列位置

问题描述

我有两张桌子。在这两个表中的每一个中,我已经使用以下命令将一列移动到第一列位置:

table1 <- 
  table1 %>%
  select(column1, everything())

然后我合并这两个表并尝试将列从第二个表移动到开头,使用:

new_table <- 
  cbind(table1, table2) %>% 
  select(column2, everything()) 

但我收到以下错误:

Error: Can't bind data because some arguments have the same name

cbind 工作只是 find 没有 select() 函数。只是不可能将 column2 移到前面。有没有办法将它移动到第二列位置?我很难在stackoverflow上找到解决方案。

另一个可重现的例子:

iris1 <- 
  iris %>%
  rename(petal.test1 = Petal.Width) %>% 
  select(petal.test1, everything()) 

iris2 <- 
  iris %>%
  rename(petal.test2 = Petal.Width) %>% 
  select(petal.test2, everything()) 

iris_total <- 
  cbind(iris1, iris2) %>%
  select(petal.test2, everything()) 

标签: r

解决方案


您可以bind_cols改用

library(dplyr)

iris1 <- 
  iris %>%
  rename(petal.test1 = Petal.Width) %>% 
  select(petal.test1, everything()) 

iris2 <- 
  iris %>%
  rename(petal.test2 = Petal.Width) %>% 
  select(petal.test2, everything()) 

iris_total <- bind_cols(iris1, iris2) %>% 
  select(petal.test2, everything()) %>% 
  as.tbl()
iris_total
#> # A tibble: 150 x 10
#>    petal.test2 petal.test1 Sepal.Length Sepal.Width Petal.Length Species
#>          <dbl>       <dbl>        <dbl>       <dbl>        <dbl> <fct>  
#>  1         0.2         0.2          5.1         3.5          1.4 setosa 
#>  2         0.2         0.2          4.9         3            1.4 setosa 
#>  3         0.2         0.2          4.7         3.2          1.3 setosa 
#>  4         0.2         0.2          4.6         3.1          1.5 setosa 
#>  5         0.2         0.2          5           3.6          1.4 setosa 
#>  6         0.4         0.4          5.4         3.9          1.7 setosa 
#>  7         0.3         0.3          4.6         3.4          1.4 setosa 
#>  8         0.2         0.2          5           3.4          1.5 setosa 
#>  9         0.2         0.2          4.4         2.9          1.4 setosa 
#> 10         0.1         0.1          4.9         3.1          1.5 setosa 
#> # ... with 140 more rows, and 4 more variables: Sepal.Length1 <dbl>,
#> #   Sepal.Width1 <dbl>, Petal.Length1 <dbl>, Species1 <fct>

reprex 包(v0.3.0)于 2019 年 11 月 22 日创建


推荐阅读