Parseltongue
Parseltongue

Reputation: 11697

Unpacking a list returned from function to multiple variables via mutate

Let's say I'm using the sentiment analyzer vader from library(vader)

For a given string it returns a named character vector with various attributes. For example,

> get_vader("How are you doing?")
                                         compound       pos       neu       neg but_count 
        0         0         0         0         0         0         1         0         0 

I want to create a vader score for a given column in my data.frame, but I want to "unpack" the pos, neu, and neg, values with a single call, rather than having to call the function three times for the same variable.

Example:

test = data.frame(a = "how are you doing today?")
test %>% mutate(vader_pos = get_vader(a)['pos'], 
vader_neg = get_vader(a)['neg'], 
vader_neu = get_vader(a)['neu']) 

How do I avoid calling the get_vader function three times, and simply unpack all three variables simultaneously to the appropriate columns?

Upvotes: 0

Views: 195

Answers (1)

Duck
Duck

Reputation: 39613

Try this:

library(vader)
#Data
test = data.frame(a = "how are you doing today?",b='Hello you')
#Create dataframe with results
df <- as.data.frame(do.call(rbind,sapply(test,get_vader)))
  V1 V2 V3 V4 V5 compound pos neu neg but_count
a  0  0  0  0  0        0   0   1   0         0
b  0  0  0  0  1        0   0   0   0         0

Upvotes: 1

Related Questions