What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table?
Solution 1
Well you could do it in 2 steps by using
# Transpose table YOU WANT
fooData.T <- t(fooData[,2:ncol(fooData)])
# Set the column headings from the first column in the original table
colnames(fooData.T) <- fooData[,1]
The result being a matrix which you're probably aware of, that's due to class issues when transposing. I don't think there will be a single line way to do this given the lack of naming abilities in the transpose step.
Solution 2
You can do it even in one line:
fooData.T <- setNames(data.frame(t(fooData[,-1])), fooData[,1])
There are already great answers. However, this answer might be useful for those who prefer brevity in code.
Solution 3
Here are my two cents using dplyr
for a data.frame
that has grouping columns and an id
column.
id_transpose <- function(df, id){
df %>%
ungroup() %>%
select(where(is.numeric)) %>%
t() %>%
as_tibble() %>%
setNames(., df %>% pull({{id}}))
}
Related videos on Youtube
themartinmcfly
Updated on January 13, 2022Comments
-
themartinmcfly over 2 years
What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table? I have coded up a way to do this below. As I am still new to R. I would like suggestions to improve my code as well as alternatives that would be more R-like. My solution is also unfortunately a bit hard coded (i.e. the new column headings are in a certain location).
# Assume a data.frame called fooData # Assume the column is the first column before transposing # Transpose table fooData.T <- t(fooData) # Set the column headings colnames(fooData.T) <- test[1,] # Get rid of the column heading row fooData.T <- fooData.T[2:nrow(fooData.T), ] #fooData.T now contains a transposed table with the first column as headings
-
Waldir Leoncio about 10 yearspossible duplicate of R-Transposing a data frame
-
-
themartinmcfly almost 13 yearsGood point, this should make it faster as far as I can tell, as it is having to transpose less data. Plus looks neater. The matrix issue is one of the issues I ran into also and had to use a class(fooData.T) <- "numeric", which won't work for any other data types.
-
themartinmcfly almost 13 yearsI am making this the answer as there aren't any other alternatives, which is strange for programming as there is usually a multitude of ways to solve something.
-
domi over 7 yearsThere is a problem with the second instruction, it should be
colnames(fooData.T) <- t(fooData[,1])