r - 在R中转置data.frame并将列之一设置为新转置表的标题的最佳方法是什么?

标签 r dataframe transpose

在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

最佳答案

那么您可以通过使用以下两个步骤来完成

# 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] 

结果是您可能知道的矩阵,这是由于转置时的类问题引起的。考虑到转置步骤中缺少命名功能,我认为不会有单一的方法可以做到这一点。

关于r - 在R中转置data.frame并将列之一设置为新转置表的标题的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6645524/

相关文章:

R - 具有来自另一个数据帧的序列的数据帧

python - 将数据框的多列值合并到一个中间带有括号的列中

基于 R 中第一列中的重复行进行 reshape

r - 如何将函数应用于 data.frame 中的行对,类似于 diff?

r - ggplot2:Stat_function 对数刻度的不当行为

嵌套函数的 R 范围规则

r - 如何从向量中删除多个值?但不是全部

r - 将 data.frame 转换为 xts order.by 需要一个适当的基于时间的对象

pandas - 如何使用 pandas 转换 df

linux - 数据混搭 : Transposing the column into rows based on group in bash