Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single value from a data frame in R

Tags:

r

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 ?

like image 973
GuitarExtended Avatar asked Oct 20 '25 15:10

GuitarExtended


1 Answers

A common application is to obtain a particular value of one variable in a data-frame given the value of one or more other column variables in the same record. For this the "filter" command can be used. It may look clunky but it works well for a large data-frame.

library(dplyr)
df
   rnames col1 col2 col3
1   row1    1    3    a
2   row2    2    6    b
3   row3    3    9    c
4   row4    4   12    d
5   row5    5   15    e

To find the value of col1 given col3 = 'c'

a <- filter(df, col3=='c')  # can specify multiple known column values
a                           #produces a data-frame with the record(s)               
 rnames col1 col2 col3
1   row3    3    9    c     # which contains Col1 = 3
class(a)
[1] "data.frame"
    

But can get value of Col1 in one line

b <- filter(df, col3=='c')$col1   
b
[1] 3
 class(b)
[1] "numeric"

For a result with multiple values

c <- filter(df, col1 > 3)$col3  
c[1] "d" "e"            # list if  > 1 result
class(c)
[1] "character"
like image 153
Wally Avatar answered Oct 22 '25 03:10

Wally



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!