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

时间:2022-07-02 12:42:06

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).

在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

2 个解决方案

#1


20  

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.

结果是你可能知道的矩阵,这是由于转置时的类问题。鉴于转置步骤中缺乏命名能力,我认为没有一种方法可以做到这一点。

#2


2  

I had a similar problem to this -- I had a variable of factors in a long format and I wanted each factor to be a new column heading; using "unstack" from the stats library did it in one step. If the column you want as a header isn't a factor, "cast" from the reshape library might work.

我有一个类似的问题 - 我有一个长格式的因素变量,我希望每个因素都是一个新的列标题;使用统计库中的“unstack”只需一步即可完成。如果您想要作为标题的列不是一个因素,重塑库中的“强制转换”可能会起作用。

#1


20  

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.

结果是你可能知道的矩阵,这是由于转置时的类问题。鉴于转置步骤中缺乏命名能力,我认为没有一种方法可以做到这一点。

#2


2  

I had a similar problem to this -- I had a variable of factors in a long format and I wanted each factor to be a new column heading; using "unstack" from the stats library did it in one step. If the column you want as a header isn't a factor, "cast" from the reshape library might work.

我有一个类似的问题 - 我有一个长格式的因素变量,我希望每个因素都是一个新的列标题;使用统计库中的“unstack”只需一步即可完成。如果您想要作为标题的列不是一个因素,重塑库中的“强制转换”可能会起作用。