在data.frame的两列之间添加(插入)一列
问题描述:
我有一个数据列,其中包含列a,b和c。我想在b和c之间添加新的列d。
I have a data frame that has columns a, b, and c. I'd like to add a new column d between b and c.
我知道我可以使用 cbind 在末尾添加d但是如何在两列之间插入?
I know I could just add d at the end by using cbind but how can I insert it in between two columns?
答
我建议您使用函数 add_column()
tibble
I would suggest you to use the function add_column()
from the tibble
package.
library(tibble)
dataset <- data.frame(a = 1:5, b = 2:6, c=3:7)
add_column(dataset, d = 4:8, .after = 2)
请注意,您可以使用列名代替列索引:
Note that you can use column names instead of column index :
add_column(dataset, d = 4:8, .after = "b")
或使用参数 .before
而不是 .after
。
add_column(dataset, d = 4:8, .before = "c")