I have what I thought was a simple task: check if a dataframe element equals a specific value.
I have data on cereal, with columns like Brand, Manufacturer, Calories, etc.
Here's an example row:
> data[1, ]
Brand Manufacturer Calories Protein Fat Sodium Fiber Carbohydrates Sugar Potassium
1 ACCheerios G 110 2 2 180 1.5 10.5 10 70
I thought this would work:
> 'G' == data[1, ]$Manufacturer
[1] FALSE
or maybe
> 'G' %in% data[1, ]$Manufacturer
[1] FALSE
but neither do.
I've checked these previous questions: Check if value is in data frame Check whether value exist in one data frame or not
Neither seems to do what I want. The only solution I've found so far is to use unlist()
on the row first, which causes the Brand / Manufacturer to become numbers
> unlist(data[1, ])
Brand Manufacturer Calories Protein Fat Sodium Fiber Carbohydrates Sugar
1.0 1.0 110.0 2.0 2.0 180.0 1.5 10.5 10.0
Potassium
70.0
and then both solutions above work fine, as long as I use 1
instead of G
.
> 1 == unlist(data[1, ])[2]
Manufacturer
TRUE
> 1 %in% unlist(data[1, ])[2]
[1] TRUE
My thought is that this isn't working because when I simply print out data[1, ]$Manufacturer
, more than just the column is returned. Something about "Levels" is returned too:
> data[1, ]$Manufacturer
[1] G
Levels: G K Q
I've tried doing data[1, ]$Manufacturer[1]
(and various other things to try and just return the G
) to no avail.
How do I do this relatively simply task?