How do I grab elements from a table in R?
My data looks like this:
V1 V2 1 12.448 13.919 2 22.242 4.606 3 24.509 0.176
etc...
I basically just want to grab elements individually. I'm getting confused with all the R terminology, like vectors, and I just want to be able to get at the individual elements.
Is there a function where I can just do like data[v1][1]
and get the element in row 1 column 1?
To access the table values, we can use single square brackets. For example, if we have a table called TABLE then the first element of the table can accessed by using TABLE[1].
Accessing a particular variable (i.e., column) in a data object is simple: DataObject$VarName , where DataObject is the data object and VarName the variable desired. The $ (dollar) symbol is how R links the requested variable to the data object. A single accessed variable is returned as a vector.
Similar to vectors and matrices, you select elements from a data frame with the help of square brackets [ ] . By using a comma, you can indicate what to select from the rows and the columns respectively. For example: my_df[1,2] selects the value at the first row and second column in my_df .
Extract value of a single cell: df_name[x, y] , where x is the row number and y is the column number of a data frame called df_name . Extract the entire row: df_name[x, ] , where x is the row number. By not specifying the column number, we automatically choose all the columns for row x .
Try
data[1, "V1"] # Row first, quoted column name second, and case does matter
Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.
There is a ton of free introductory material for beginners in R: CRAN: Contributed Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With