Brian D
Brian D

Reputation: 79

First row and column as headers for table in r

I have a table and I want the top row and the first column as headers (title row and column) for the table. I have a picture of what I want and the dput code below:

Picture of what I want


Dput code below:

structure(c("TIDM", "12m yield", "Net assets (fund)", "Currency (prices)", 
"12m yield", "XDGU", "3.89", "1,287.40", "USD", "3.89", "AT1D", 
"5.48", "485.934", "GBP", "5.48", "PRFD", "4.63", "141.309", 
"USD", "4.63", "PRFP", "4.63", "141.309", "GBP", "4.63"), .Dim = c(5L, 
5L), .Dimnames = list(c("V1", "V2", "V3", "V4", "V5"), NULL))

Upvotes: 0

Views: 88

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389345

You can use :

#Convert to dataframe if needed
df <- data.frame(df)
#Add rownames
rownames(df) <- make.unique(df[, 1])
#Add column names
colnames(df) <- df[1, ]
#We remove data from 1st row and 1st column
df <- df[-1, -1]
df

#                      XDGU    AT1D    PRFD    PRFP
#12m yield             3.89    5.48    4.63    4.63
#Net assets (fund) 1,287.40 485.934 141.309 141.309
#Currency (prices)      USD     GBP     USD     GBP
#12m yield.1           3.89    5.48    4.63    4.63

We use make.unique to create unique names since we cannot have duplicate rownames in the data. You can remove the 1st line if you want to keep data as matrix.

Upvotes: 1

Related Questions