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 of 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:
The general pattern is
[r, c]whererindexes the rows, andcindexes 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.Notice that for the first of those, R has dropped the empty dimension resulting in a vector. To suppress this behaviour, add
drop = FALSEto the call: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: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.frameor?`[[.data.frame`