R中代码段的含义

时间:2017-04-04 01:58:02

标签: r

我正在调试我在网上找到的代码,以便对其进行调试。其中一条是:

z = train[train[,11]==i, 1:10]

其中train定义为:

train = matrix(0,nrow(y)/2,ncol(y))

y是来自.csv文件的输入数据(以矩阵形式)。该代码用于从.csv表单中给出的输入数据中训练分类器。该文件仅包含01 s。

train[,11]==i不会返回布尔值吗?如何通过布尔参数访问train矩阵?

1 个答案:

答案 0 :(得分:2)

让我们分解:

# Create some data and a value to look for
> train <- matrix(1:121,11)
> i = 112

# This is a vector of column 11 of the matrix
> train[,11]
[1] 111 112 113 114 115 116 117 118 119 120 121

# This is a vector of the same length as column 11 of the
# matrix with TRUE/FALSE depending on if the value equals i
> train[,11]==i
[1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

# Finally, this is then selecting the rows that had a TRUE
# value. So if the 2nd item in the column above is 112 (it is)
# then only the second value in the vector will be TRUE, so it
# will select the second row (could be more rows with different
# data in the matrix of course). It also selects only the first
# ten columns of that row, i.e. 1:10.
> train[train[,11]==i, 1:10]
[1]   2  13  24  35  46  57  68  79  90 101

基本上,您可以使用布尔向量进行选择。它也将按照您的预期进行换行,因此下一个示例将使用TRUE然后为FALSE,然后为TRUE,然后为FALSE,直到达到10。

x <- 1:10
x[c(T,F)]