简体   繁体   English

在 R 的 dataframe 的某些位置添加多列

[英]Adding multiple columns at certain positions in dataframe in R

I have a dataframe that looks similar to this one:我有一个 dataframe 看起来类似于这个:

> df <- data.frame(A1=1:3, B1=1:3, A2=1:3, B2=1:3, A3=1:3, B3=1:3)
> df

  A1 B1 A2 B2 A3 B3
1  1  1  1  1  1  1
2  2  2  2  2  2  2
3  3  3  3  3  3  3

Now, I'm looking for some code that adds rows before B1, B2 and B3:现在,我正在寻找一些在 B1、B2 和 B3 之前添加行的代码:

  A1 AB1 B1 A2 AB2 B2 A3 AB3 B3
1  1   X  1  1   X  1  1   X  1
2  2   X  2  2   X  2  2   X  2
3  3   X  3  3   X  3  3   X  3

As the dataframe above is only a minimum, reproducible example (the real dataframe is much larger), I'm looking for a solution either using a for loop or a solution with tidyverse.由于上面的 dataframe 只是一个最小的、可重现的示例(真正的 dataframe 更大),我正在寻找使用 for 循环或具有 tidyverse 的解决方案的解决方案。 I had the idea to use a combination of a for loop and add_column from the tibble package:我的想法是使用来自 tibble package 的 for 循环和add_column的组合:

library(tibble)
  
  for (i in 1:3) {
    df <- df %>%
      add_column(paste0("AB", i, "") = "X" , .before = paste0("B", i, ""))
  }

Unfortunately, the idea does not work.不幸的是,这个想法行不通。 I'm not quite sure if the whole approach is wrong, or if there is anything wrong with the paste0() etc.. If you need any further information, please let me know.我不太确定整个方法是否错误,或者paste0()等是否有任何问题。如果您需要任何进一步的信息,请告诉我。 T

With a slight tweak your code works although there's probably better ways to do this:稍作调整,您的代码就可以工作,尽管可能有更好的方法来做到这一点:

for (i in 1:3) {
  df <- df %>%
    add_column(!!paste0("AB", i, collapse = "") := "X" , .before = paste0("B", i, collapse =  ""))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM