David Geismar
David Geismar

Reputation: 3422

R shifting values of dataframe to the left while preserving headers

I have a csv file with headers in the form :

a,b,c,d
1,6,5,6,8

df <- read_csv("test.csv")

For some reason there's the value 1 in the example is incorrect and to correct the file, Id like to shift all the other values to the left and thus drop 1 but preserving the columns ending with :

a,b,c,d
6,5,6,8

How can I achieve that ?

Upvotes: 0

Views: 61

Answers (2)

Geoffrey Poole
Geoffrey Poole

Reputation: 1298

In one line of code, the structure command creates an object and assigns attributes:

structure(df[,2:length(df)], names = names(df)[1:(length(df)-1)])

Recognizing that a data.frame is a list of equal-length vectors, where each vector represents a column, the following will also work:

structure(df[2:length(df)], names = names(df)[1:(length(df)-1)])

Note no comma in df[1:length(df)].

Also, I like the trick of removing items from a vector or list using a negative index. So I think an even cleaner bit of code is:

structure(df[-1], names = names(df)[-length(df)])

Upvotes: 0

Javier
Javier

Reputation: 457

What about this:

headers <- names(df)
new_df <- df[, 2:length(df)]
names(new_df) <- headers

Upvotes: 1

Related Questions