开发者

Direct access to Vector elements in a data.frame in R?

Is it possible to directly access elements of vectors in a 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 o开发者_开发问答f the column
nerv$c.1.10.[5]

I tried several things, but none of them worked. I just have the index of the column but not the name, since I want to interate several columns using a loop.

It seems that I have a basic knowledge gap and I hope you can help me to fill it.


You want:

> nerv[5,2]
[1] 5

The general pattern is [r, c] where r indexes the rows, and c indexes the columns/variables, that you want to extract. One or both of these can be missing, in which case, it means give me all of the rows/columns that do not have indexes. E.g.

> 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

Notice that for the first of those, R has dropped the empty dimension resulting in a vector. To suppress this behaviour, add drop = FALSE to the call:

> 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

We can also use the list-style notation in extracting components of the data frame. [ will extract the component (column) as a one-column data frame, whilst [[ will extract the same thing but will drop dimensions. This behaviour comes from the usual behaviour on a list, where [ returns a list, whereas [[ returns the thing inside the indexed component. Some example might help:

> 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

This also explains why nerv[2][5] failed for you. nerv[2] returns a data frame with a single column, which you then try to retrieve column 5 from.

The details of this are all included in the help file ?Extract.data.frame or ?`[[.data.frame`


Since a data frame is technically a list, this also works:

nerv[[2]][5]


try

nerv[5,2]

and...

?'['

This should help fill in your gap a bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜