I'm using the fb_insights
from the package fbRads like this: (I use more metrics in my real problem)
fb_campaigns <- rbindlist(lapply(l, function(l) cbind(Campaign = l$campaign_name, rbindlist(l$actions))))
Oh, and I get some warnings (I know I'm doing something wrong, but can't solve it):
Warning messages:
1: In data.table::data.table(...) :
Item 1 is of size 11 but maximum size is 104 (recycled leaving remainder of 5 items)
The result is the data frame with all the data I need (Campaign, action_type, value), but... the columns with the "action_types" and their numbers came out of order. The action data don't seem to be from the campaigns in the rows.
How can I merge the action types with the campaigns?
After I the data in the correct rows, I will use reshape to make the action_types columns with the values.
The data I get from fb Rads and I want to transform are like this:
The data I get using my code are like this (the format is OK, but not the order of the values, they are not the values for the campaigns)
daroczig give me the solution bellow, and seems to work fine!
## list of action types to extract
actiontypes <- c('link_click', 'comment', 'like', 'post')
## extract actions from the data returned by the Insights API
lactions <- unlist(lapply(l, function(x) x$actions), recursive = FALSE)
## extract fields from the actions
library(data.table)
lactions <- rbindlist(lapply(lactions, function(actions) {
setnames(as.data.table(
do.call(cbind,
lapply(actiontypes,
function(action) {
if (is.null(actions)) return(0)
value <- subset(actions, action_type == action, value)
if (nrow(value) == 0) return(0) else
return(value[[1]])
}))),
actiontypes)
}))
## Merging the dataframe with the original data and the dataframe with the actions
fb_campaigns <- cbind(l[,c(1,4:11)],lactions))