我正在使用“pls”包,为此我需要生成一个结构与我习惯的有点不同的数据框。
我需要使用“请:汽油”的数据框架结构
library(pls)
gasoline
显示我的数据的示例:汽油2
背景信息 - 将数据加载到 R 中时,我倾向于将数据转录为 .xls,然后将文件转换为 .txt,然后将其加载到 R。
当我的数据加载时,它看起来像这样:
gasoline2 <- as.data.frame(as.matrix(gasoline))
问题
如何将汽油2的结构转换为汽油的结构?
预先非常感谢您的帮助!
最佳答案
您正在寻找I
,它允许您将不同的数据结构(例如列表
或矩阵)组合为data.frame中的列
:
## Assume you are starting with this:
X <- as.data.frame(as.matrix(gasoline))
## Create a new object where column 1 is the same as the first
## column in your existing data frame, and column 2 is a matrix
## of the remaining columns
newGas <- cbind(X[1], NIR = I(as.matrix(X[-1])))
str(gasoline)
# 'data.frame': 60 obs. of 2 variables:
# $ octane: num 85.3 85.2 88.5 83.4 87.9 ...
# $ NIR : AsIs [1:60, 1:401] -0.050193 -0.044227 -0.046867 -0.046705 -0.050859 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr "1" "2" "3" "4" ...
# .. ..$ : chr "900 nm" "902 nm" "904 nm" "906 nm" ...
str(newGas)
# 'data.frame': 60 obs. of 2 variables:
# $ octane: num 85.3 85.2 88.5 83.4 87.9 ...
# $ NIR : AsIs [1:60, 1:401] -0.050193 -0.044227 -0.046867 -0.046705 -0.050859 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr "1" "2" "3" "4" ...
# .. ..$ : chr "NIR.900 nm" "NIR.902 nm" "NIR.904 nm" "NIR.906 nm" ...
列命名略有不同,但我认为这很容易解决......
> colnames(newGas$NIR) <- gsub("NIR.", "", colnames(newGas$NIR))
> identical(gasoline, newGas)
[1] TRUE
关于r - 将矩阵嵌入一个变量的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878449/