Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does column exist and how to rearrange columns in R data frame

Tags:

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.

like image 710
JD Long Avatar asked Jul 24 '09 14:07

JD Long


People also ask

How do I rearrange the order of columns in a Dataframe in R?

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.

Can you change order of columns in R?

Use relocate() to change column positions, using the same syntax as select() to make it easy to move blocks of columns at once.

How do I move a column position in R?

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.


2 Answers

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")] 
like image 172
hadley Avatar answered Sep 25 '22 10:09

hadley


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 >  
like image 26
Dirk Eddelbuettel Avatar answered Sep 23 '22 10:09

Dirk Eddelbuettel