R
函数成功地转移了数据框。但是,我想将列名和行名称更改为DataFrame的一部分。我将以虹膜数据为例。
# Transpose iris data
iris.transposed <- t(iris)
# View the transposed DF
View(iris.transposed)
在附加的屏幕截图中,df df中的列标头包含列
V1, V2, V2, V4,
E.T.C。但是,我希望行species
到列标题。
行也是如此。 Sepal.length, sepal.width, petal.length..
E.T.C是Rownames。但是,我希望它们成为数据框架的一部分。
我如何最终确定?
像这样的东西?
# remove the last column, it's not a numeric column, it's a factor
iris.transposed <- t(iris[-5])
# the first argument of ave() tells the return value class
new_names <- ave(as.character(iris[[5]]), iris[[5]], FUN = \(x) paste0(x, seq_along(x)))
colnames(iris.transposed) <- new_names
# see the matrix structure
str(iris.transposed)
#> num [1:4, 1:150] 5.1 3.5 1.4 0.2 4.9 3 1.4 0.2 4.7 3.2 ...
#> - attr(*, "dimnames")=List of 2
#> ..$ : chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
#> ..$ : chr [1:150] "setosa1" "setosa2" "setosa3" "setosa4" ...
用Rreprexv2.1.1
于2025-02-11创建