转置R中的data.frame并将其中一列设置为新转置的表头的最佳方法是什么?我已经在下面编写了一种方法来实现这一点。因为我仍然是R的新手,所以我想要一些建议来改进我的代码,以及更像R的替代方案。不幸的是,我的解决方案也有点硬编码(即新的列标题位于某个位置)。
# 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
发布于 2011-07-11 11:51:37
好的,你可以用两个步骤来完成它,使用
# 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]
结果是一个你可能知道的矩阵,这是由于转置时的类问题。考虑到转置步骤中缺乏命名能力,我认为不会有一种简单的方法来实现这一点。
发布于 2021-01-07 22:55:52
以下是我对data.frame
使用dplyr
的两点建议,该and具有分组列和id
列。
id_transpose <- function(df, id){
df %>%
ungroup() %>%
select(where(is.numeric)) %>%
t() %>%
as_tibble() %>%
setNames(., df %>% pull({{id}}))
}
发布于 2021-06-29 07:38:08
你甚至可以用一行代码来实现:
fooData.T <- setNames(data.frame(t(fooData[,-1])), fooData[,1])
已经有很好的答案了。但是,对于那些更喜欢代码简洁的人来说,这个答案可能很有用。
https://stackoverflow.com/questions/6645524
复制相似问题