2017-10-20 89 views
0

在矩陣中引用單個單元格的語法是什麼?我想引用R data.frame中的單個單元格來創建函數。例如,假設我有一個值data.frame或矩陣中的引用單元格以創建函數

3 4 
5 6 

一個2x2矩陣,我想創建一個函數,將做((3 + 4)/(3 + 4 + 5))。我嘗試過將它作爲一個函數,並且創建一個新的變量而沒有成功。

Subj_2_block_4a$HRLR0 <- c(2,2)+c(2,4)給我四個觀察下一個新的變量。

Subj_2_block_4a$HRLR0 <- ((2:2 + 2:4)/(2:2 + 2:4 + 2:1 +2:3))將這些作爲對矩陣而不是單元格的引用。

Subj_2_block_4a$HRLR0 <- nrow2:ncol2 + nrow2:ncol4;根本不起作用。

我發現大量資源用於添加不同矩陣中的列或行,但尚未找到任何有關如何使用一個矩陣內的單元格編寫數學函數的明確說明。

+0

剛剛更新我的回答對你表現出更多的方法,使參考特定細胞..看看 – Thai

回答

1

在矩陣使引用元素

如果你想建立一個矩陣,你做

mtrx <- matrix(c(3,4,5,6), # the data elements 
       nrow=2,    # number of rows 
       ncol=2,    # number of columns 
       byrow = TRUE)  # will format in the way you want 

#Take a look in your matrix by just doing this: 

mtrx      # print your matrix 
>  [,1] [,2] 
> [1,] 3 4  
> [2,] 5 6 

而且finaly,如果你想在行X引用的元素,第Y列,可以通過mtrx [X,Y]訪問。你的情況:

# Your second row, second col: 

mtrx[2, 2]  # element at 2nd row, 2rd column 
> [1] 6 

如果你想看到整個行或整列,這是可能太

mtrx[2, ] # entire second row 
mtrx [ ,2] # entire second column 

而且你還可以同時提及一個以上的元素。 ..允許在數據幀中創建該

#Creating a 3x3 matrix 
Lmtrx<-matrix(c(3,4,5,6,7,8,1,2,6),ncol = 3,nrow = 3, byrow = TRUE) 
Lmtrx # prit to take a look 

#Making reference to two columns at once: 1rst and 3rd 
Lmtrx[ ,c(1,3)] 

製作參考較大矩陣的CEL

要參考在data.frame,而不是一個矩陣的單元格,是很容易的,以及:

df$col1[1] # First row in first column 
df[1,1] # First row in first column, another way to get it 
df$col1 # entire first column 
df[ ,1] # entire first column, another way to get it 
df[1, ] # entire first row 
相關問題