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.
I know I could just add d at the end by using cbind but how can I insert it in between two columns?
Answer. Yes, you can add a new column in a specified position into a dataframe, by specifying an index and using the insert() function. By default, adding a column will always add it as the last column of a dataframe. This will insert the column at index 2, and fill it with the data provided by data .
To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values .
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")
Or use argument .before
instead of .after
if more convenient.
add_column(dataset, d = 4:8, .before = "c")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With