How do I add a column in the middle of an R data frame? I want to see if I have a column named "LastName" and then add it as the third column if it does not already exist.
Use select() function from dplyr package to reorder or change the order of columns in R, to use select() function, you have to install dplyr first using install. packages('dplyr') and load it using library(dplyr) . All functions in dplyr package take data. frame as a first argument.
Use relocate() to change column positions, using the same syntax as select() to make it easy to move blocks of columns at once.
The easiest way to move the data frame column to a specific position in R is by using the function relocate from package dplyr. It is common for me that after creating a new column, I want that to move to a specific location in the R data frame.
One approach is to just add the column to the end of the data frame, and then use subsetting to move it into the desired position:
d$LastName <- c("Flim", "Flom", "Flam") bar <- d[c("x", "y", "Lastname", "fac")]
1) Testing for existence: Use %in% on the colnames, e.g.
> example(data.frame) # to get 'd' > "fac" %in% colnames(d) [1] TRUE > "bar" %in% colnames(d) [1] FALSE
2) You essentially have to create a new data.frame from the first half of the old, your new column, and the second half:
> bar <- data.frame(d[1:3,1:2], LastName=c("Flim", "Flom", "Flam"), fac=d[1:3,3]) > bar x y LastName fac 1 1 1 Flim C 2 1 2 Flom A 3 1 3 Flam A >
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