How to iterate over data.frame in R

Viewed 59

I have the following data.frame, call it Fruits

    fruit  amount
1   apple  5
2   cherry 6
3   kiwi   20
4   banana 4
5   orange 12

I also have the following event

>G
 [1] "apple" "kiwi" "orange"

How can I find the total amount by iterating over each fruit in G is my question?

I understand that Fruits[1, 2] gives me 5 (column 2 row 1) but how do I use that to do what I need?

3 Answers

Try this:

with(Fruits, sum(amount[fruit %in% G]))

You can try this solution:

> sum(df$amount[match(G,df$fruit)])
[1] 37
> 

You can use subset, sum, and %in%:

sum(subset(dt, fruit %in% G, amount))
#R> [1] 37

or

sum(subset(dt, fruit %in% G)$amount)
#R> [1] 37

Data

dt <- data.frame(fruit  = c("apple", "cherry", "kiwi", "banana", "orange"),
                 amount = c(5      , 6       , 20    , 4       , 12      ))
G <- c("apple", "kiwi", "orange")
Related