Get a single value from a data frame in R

r

Solution

R will get out of its way to try to figure out what you want. If you coerce to character, it should work. Here's a quick example.

> xy <- data.frame(a = c(0.1, 0.2, 0.3), b = factor(1:3), c = letters[1:3])
> 
> xy$a == 0.1
[1]  TRUE FALSE FALSE
> xy$a == "0.1"
[1]  TRUE FALSE FALSE
> xy$b == "2"
[1] FALSE  TRUE FALSE
> xy$b == 2
[1] FALSE  TRUE FALSE
> xy$c == "a"
[1]  TRUE FALSE FALSE

Problem

Say I have a data frame df such as : ``` col1 col2 x1 y1 x2 y2 ``` with arbitrary values in each "cell". How do I get a single value for a given cell ? For instance to get the value of the cell in the first row and second column, doing this : ``` df[1,2] ``` works with numeric values, but with strings it return the levels as well. What is the proper way of getting a single value (for instance for use in a condition for a subset of another data frame) ? EDIT More details about what I need this for. Say I need to use values from df to subset another data frame df2 : ``` subset(df2, (id == SomeCommand(df[1,1])) & (name == SomeCommand(df[1,2]))) ``` Is there any such "SomeCommand" that would reliably return a single value (w/o levels) of the appropriate type regardless of the type of the columns in df ?

Original source