在 data.frame 的两列之间添加(插入)一列 [英] Add (insert) a column between two columns in a data.frame

查看:73
本文介绍了在 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?

推荐答案

我建议你使用 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.

Or use argument .before instead of .after if more convenient.

add_column(dataset, d = 4:8, .before = "c")

这篇关于在 data.frame 的两列之间添加(插入)一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆