gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:29:41 24 4
gpt4 key购买 nike

在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com