2015-04-26 45 views
2

我正在使用'pls'包,爲此我需要生成一個結構與我以前不同的數據幀。矩陣嵌入到一個變量中的數據幀

數據幀結構我需要「請工作:汽油

library(pls) 
gasoline 

例子來說明我的數據看起來像:gasoline2

背景信息 - 我傾向於做加載數據爲R是抄本中的數據的.xls,然後將文件轉換爲.txt,然後將其加載到R.

當我的數據加載它看起來像這樣:

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

問題

如何將汽油2的結構轉換成汽油結構?

非常感謝您的幫助!

+0

你爲什麼傾向於將它寫入Excel? –

+0

我發現第一次引入數據更容易...您是否以不同的方式引入數據? :) – user3262756

+0

我該怎麼做?你把它介紹給誰?我通常使用'View'來查看數據。 –

回答

2

您正在尋找I,這將允許您爲列在不同的數據結構(如list S或矩陣)結合了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 
+0

非常感謝,正是我需要做的! – user3262756

相關問題