YellowRiver
YellowRiver

Reputation: 75

apply function by name of list

Imagine that I have a list

l <- list("a" = 1, "b" = 2)

and a data frame

id   value
 a       3
 b       4

I want to match id with list names, and apply a function on that list with the value in data frame. For example, I want the sum of value in the data frame and corresponding value in the list, I get

 id   value 
  a    4
  b    6

Anyone has a clue?

Edit: A. I just want to expand the question a little bit with. Now, I have more than one value in every elements of list.

l <- list("a" = c(1, 2), "b" =c(1, 2))

I still want the sum

  id   value 
   a     6
   b     7

Upvotes: 1

Views: 249

Answers (2)

BENY
BENY

Reputation: 323236

You just need

df$value=df$value+unlist(l)[df$id]# vector have names can just order by names 
df
  id value
1  a     4
2  b     6

Try answer with Ronak

l <- list("b" = 2, "a" = 1)

unlist(l)[as.character(df$id)]# if you id in df is factor 
a b 
1 2 

Update

df$value=df$value+unlist(lapply(l,sum))[df$id]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

We can match the names of the list with id of dataframe, unlist the list accordingly and add it to value

df$value <- unlist(l[match(df$id, names(l))]) + df$value

df
#  id value
#1  a     4
#2  b     6

EDIT

If we have multiple entries in list we need to sum every list after matching. We can do

df$value <- df$value + sapply(l[match(df$id, names(l))], sum)
df

#  id value
#1  a     6
#2  b     7

Upvotes: 4

Related Questions