本文介绍了在R中转置data.frame并将列之一设置为新转置表的标题的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中转置data.frame并将列之一设置为新转置表的标题的最佳方法是什么?我已经在下面编写了执行此操作的方法。由于我仍然不熟悉R。我想提出一些改进我的代码的建议,以及一些更像R的替代方案。不幸的是,我的解决方案也经过了硬编码(即新列标题位于某个位置)。

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


推荐答案

那么您可以通过使用以下两个步骤来做到这一点

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] 

结果是一个您可能知道的矩阵,这是由于cl转置时出现屁股问题。考虑到转置步骤中缺少命名功能,我认为不会有任何一行方法可以做到这一点。

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.

这篇关于在R中转置data.frame并将列之一设置为新转置表的标题的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 12:24