Reputation: 508
I would like to replace the header of a data.frame by a header in the first row. The data has been imported with read.xls(). Reading in the original file again is unfortunately no option.
bad header here
1 new header2 here
2 58 3.222 50
3 25 10.000 40
4 5 0.847 152.5
5 15 1.633 98
The result should look like this:
new header2 here
1 58 3.222 50
2 25 10.000 40
3 5 0.847 152.5
4 15 1.633 98
Thanks,
Matt
Upvotes: 0
Views: 2067
Reputation: 162
Assuming your data is called my.data.frame just assign row 1 to the header and then delete row 1
#assign row 1 names to the header
names(my.data.frame) <- as.character(my.data.frame[1,])
#delete the first row
my.data.frame <- my.data.frame[2:nrow(my.data.frame),]
Upvotes: 1
Reputation: 193527
Assuming your data.frame
is called "mydf", you can try something like this:
df2 <- setNames(mydf[-1, ], mydf[1, ])
However, your data will all be character or factor depending on how they were initially read in.
str(df2)
# 'data.frame': 4 obs. of 3 variables:
# $ new : chr "58" "25" "5" "15"
# $ header2: chr "3.222" "10.000" "0.847" "1.633"
# $ here : chr "50" "40" "152.5" "98"
You can convert that as follows:
df2[] <- lapply(df2, function(x) type.convert(as.character(x)))
str(df2)
# 'data.frame': 4 obs. of 3 variables:
# $ new : int 58 25 5 15
# $ header2: num 3.222 10 0.847 1.633
# $ here : num 50 40 152 98
df2
# new header2 here
# 2 58 3.222 50.0
# 3 25 10.000 40.0
# 4 5 0.847 152.5
# 5 15 1.633 98.0
Upvotes: 2