Arrays 直接访问R中data.frame中的矢量元素?

Arrays 直接访问R中data.frame中的矢量元素?,arrays,r,vector,types,Arrays,R,Vector,Types,可以直接访问data.frame中的向量元素吗 # DataFrame nerv <- data.frame( c(letters[1:10]), c(1:10) ) str(nerv) # Accessing 5th element of the second variable/column # This should give "5", but it does NOT work nerv[2][5] # Works, but I need to know the

可以直接访问data.frame中的向量元素吗

# DataFrame
nerv <- data.frame(
    c(letters[1:10]),
    c(1:10)
)

str(nerv)

# Accessing 5th element of the second variable/column
# This should give "5", but it does NOT work
nerv[2][5]

# Works, but I need to know the NAME of the column
nerv$c.1.10.[5]
#数据帧
神经试试看

而且

?'['
这将有助于填补您的空缺。

您需要:

> nerv[5,2]
[1] 5
一般模式是
[r,c]
,其中
r
索引要提取的行,而
c
索引要提取的列/变量。其中一个或两个可能丢失,在这种情况下,这意味着给我所有没有索引的行/列。例如

> nerv[, 2] ## all rows, variable 2
 [1]  1  2  3  4  5  6  7  8  9 10
> nerv[2, ] ## row 2, all variables
  c.letters.1.10.. c.1.10.
2                b       2
请注意,对于其中的第一个,R删除了空维度,从而生成了一个向量。要抑制此行为,请在调用中添加
drop=FALSE

> nerv[, 2, drop = FALSE] ## all rows, variable 2
   c.1.10.
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9
10      10
我们还可以在提取数据帧的组件时使用列表样式的表示法
[
将提取组件(列)作为一列数据帧,而
[
将提取相同的内容,但会删除维度。此行为来自列表上的常见行为,其中
[
返回列表,而
[
返回索引组件内的内容。一些示例可能有助于:

> nerv[2]
   c.1.10.
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9
10      10
> nerv[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10
> nerv[[1:2]]
[1] 2
这也解释了
nerv[2][5]
失败的原因。
nerv[2]
返回一个包含单列的数据帧,然后尝试从中检索列5


这方面的详细信息都包含在帮助文件
?Extract.data.frame
?`[.data.frame`

中,因为从技术上讲,数据框是一个列表,所以这也适用于:

nerv[[2]][5]

我已经试过了
nerv[2,5]
,但是它给出了
NULL
。我也试过像
as.vector(nerv[2])[5]
这样的东西,从后到前,行第一,列第二。你们两个都有错误。@Gavin,我肯定@John打错了…[修复].@aL3xa哎哟,对不起,我应该把它改成灰色的。@John,对不起,我不是故意这么急躁的。我猜我确实打错了…:)谢谢aL3xa
nerv[[2]][5]