【问题标题】:Data frame with matrix embedded in one variable一个变量中嵌入矩阵的数据框
【发布时间】:2015-04-26 13:47:34
【问题描述】:

我正在使用“pls”包,为此我需要生成一个结构与我习惯的有点不同的数据帧。

我需要使用“pls:gas”的数据框结构

library(pls)
gasoline

显示我的数据的示例:gasal2

背景信息 - 我倾向于将数据加载到 R 中是将数据转录为 .xls,然后将文件转换为 .txt,然后将其加载到 R。

当我的数据被加载时,它看起来像这样:

gasoline2 <- as.data.frame(as.matrix(gasoline))

问题

如何将gas2的结构转化为汽油的结构?

非常感谢您的帮助!

【问题讨论】:

  • 您为什么倾向于将其写入 Excel?
  • 我发现第一次引入数据更容易......您引入数据的方式不同吗? :)
  • 我该怎么做?你介绍给谁?我通常使用View 来查看数据。
  • @DavidArenburg,您是否尝试过在以矩阵为列的数据集上使用View? :-)
  • @AnandaMahto 我仍然看不到使用 Excel 的意义。可以简单地做gasoline2 &lt;- as.data.frame(as.matrix(gasoline)) ; View(gasoline2) 还是我在这里遗漏了什么?

标签: r matrix data-structures dataframe


【解决方案1】:

您正在寻找I,它允许您将不同的数据结构(如lists 或矩阵)组合为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

【讨论】:

  • 非常感谢,正是我需要做的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多