Assuming that the data is stored in a data.frame df1
df1 <- read.table(text="Name XYZ AGE 30 Country India Mobile 1234567890
Name ABC AGE 35 Country Russia Mobile 2345678901")
You could create a new data.frame df2
by selecting every second (even-numbered) column
df2 <- df1[c(FALSE,TRUE)]
and assign the column names by using every second (odd-numbered) entry in the first row of df1
:
colnames(df2) <- unlist(df1[1, c(TRUE, FALSE)])
The data.frame df1
can then be deleted with rm(df1)
. This is the result for df2
:
#> df2
# Name AGE Country Mobile
#1 XYZ 30 India 1234567890
#2 ABC 35 Russia 2345678901
The same procedure could be written as a one-liner. Arguably less clear, but certainly more compact:
df1 <- `colnames<-`(df1[c(FALSE,TRUE)], unlist(df1[1,c(TRUE,FALSE)]))
In that case the second data.frame df2
is not needed.