How to insert a column between two columns in R

r
data_wrangling

#1

Hello,

I have a dataset where there is an incident_date and a dob column.I want to insert an age column between these two.The data should look like:
<img src="/uploads/analyticsvidhya/original/1X/60dfb88a9f391e12ea9257efaa1dedf0afa0c00d.png" width=“690” height=“387”

I do not want to use cbind. :smile:r


#2

Add in your new column:

df$d <- list/data
Then you can reorder them.

df <- df[,c(“a”,“b”,“d”,“c”)]

source-


#3

You can simply reinitialize the matrix. For instance,
mat <- your_matrix
mat <- rbind(your_matrix$firstpart,new_colyour_matrix$secondpart)

Hope this help.


#4

I think you meant to use the cbind() function instead of the rbind() function. Also, the OP specifically said he did not want to use the cbind() function.


#5

Hi

if bind() is not possible to use go with dplyr::bind_cols(). Deployer is fast and can handle quite big tables.

Alain


#6

The OP does not want a solution with the cbind() function even though I think it is the easier way to achieve the desired result. I will provide a code that can be copied and pasted and will also provide some comments to help explain what it does. Also, ajay_ohri gave a solution before me, which works but which, I believe could be tedious if the data frame has many columns. But again, it works!

# Create a hypothetical data frame with 20 rows and 10 columns whose column names are the first 10 letters of the alphabet

 set.seed(123)
df <- as.data.frame(replicate(10, rnorm(20)))
dfnames <- letters[1:ncol(df)]
colnames(df) <- dfnames

# Here is the column we want to insert in the data frame
        
        x <- 1:nrow(df)
        
# And we assume that we want to insert 'x' as the third column
        
index <- 3
        
# Let's create a loop that will shift each column from the current third column one step to the right
        
for(i in rev(index:ncol(df)) + 1) df[,i] <- df[,i-1]
mydf[,index] <- x
colnames(df) <- c(dfnames[1:(index-1)], "x", dfnames[ind:length(dfnames)])

Do not hesitate to post a reply to this message for improvements and/or questions.


#7

library(tibble)
add_column(original_dataframe_name, new_column_that_needs_to_be_inserted, .after = 10)

here 10 indicates the position of the new column . you can change it as per the position needed

its worth noting, that there is a period (.) that is prefixed with after (.after)