gpt4 book ai didi

arrays - 直接访问R中data.frame中的Vector元素?

转载 作者:行者123 更新时间:2023-12-01 15:14:43 26 4
gpt4 key购买 nike

是否可以直接访问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`

关于arrays - 直接访问R中data.frame中的Vector元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com