data.frame或矩阵中的引用单元格以创建函数
问题描述:
在矩阵中引用单个单元格的语法是什么?我想引用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
;根本不起作用。
我发现大量资源用于添加不同矩阵中的列或行,但尚未找到任何有关如何使用一个矩阵内的单元格编写数学函数的明确说明。
答
在矩阵使引用元素
如果你想建立一个矩阵,你做
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
刚刚更新我的回答对你表现出更多的方法,使参考特定细胞..看看 – Thai