r - 将矩阵嵌入一个变量的数据框

标签 r matrix data-structures dataframe

我正在使用“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/

相关文章:

r - 在 R 中,根据元素名称重组列表(rbind 和指示变量)

r - 如何消除bigglm中的 “NA/NaN/Inf in foreign function call (arg 3)”

r - 为什么 dplyr::filter 不允许我过滤两个垂直方向?

r - 在R中将因子矩阵转换为二进制(指标)矩阵的最有效方法

r - 如何更有效地将巨大的向量列表转换为矩阵?

java - 映射条目出现在 HashMap.entrySet() 中,但不在内部 HashMap.table 中

r - 按值进行子集化后改变列

java - 结果矩阵的输出无法正确显示

java - 计算从 167.37 美元中赚取(钱)零钱的不同方式?

java - 寻找类似表的数据结构