Reputation: 2890
I am trying to change the names of specific columns of a data frame in R. for example, If i have a data frame that looks something like this:
df <- data.frame(
x1 = rnorm(10),
y1 = rnorm(10),
x2 = rnorm(10),
y2 = rnorm(10),
x3 = rnorm(10),
y3 = rnorm(10)
)
head(df,3)
x1 y1 x2 y2 x3 y3
1 -1.42423743 0.21855807 -0.1456853 1.46204179 1.6474040 2.2384782
2 1.17158831 -1.41602524 -1.2891551 1.45028848 -1.2726250 -0.3331051
3 -0.21959357 0.84741665 0.2745170 0.81040227 -0.3520883 -0.3103068
What I want to do is change the names of all the y columns (i.e., y1, y2, y3) to just simply y. So the resulting data frame would look like this:
x1 y x2 y x3 y
1 -1.42423743 0.21855807 -0.1456853 1.46204179 1.6474040 2.2384782
2 1.17158831 -1.41602524 -1.2891551 1.45028848 -1.2726250 -0.3331051
3 -0.21959357 0.84741665 0.2745170 0.81040227 -0.3520883 -0.3103068
I realise there's now multiple y-columns in the data frame, but for my purposes it's necessary.
Im not sure how to do this, but I was thinking of looping through the df and changing the column names... this code doesn't work, but I was thinking of something like this:
for(j in 1:length(df)){
colnames(df$[j])[which(names(df$[j]) == "y[j]")] <- "y"
}
Any suggestion as to how I'd achieve this?
Upvotes: 3
Views: 112
Reputation: 388797
It is not advised to have multiple columns with same name but if you still have to do here is one way
names(df)[grep("^y", names(df))] <- "y"
Or a regex-free approach
names(df)[startsWith(names(df), "y")] <- "y"
Upvotes: 4