获取带有列表的列并与 R 中的其他列合并 - 使用 fbRads

Getting a column with a list and merging with the others in R - With fbRads

我正在使用包 fbRads 中的fb_insights,如下所示:(我在实际问题中使用了更多指标)

fb_campaigns <- rbindlist(lapply(l, function(l) cbind(Campaign = l$campaign_name, rbindlist(l$actions))))

哦,我收到一些警告(我知道我做错了什么,但无法解决):

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)

结果是包含我需要的所有数据(Campaign、action_type、值)的数据框,但是...带有 "action_types" 的列及其编号出现了乱序。操作数据似乎不是来自行中的广告系列。

如何将操作类型与活动合并?

在正确的行中输入数据后,我将使用重塑使 action_types 列具有值。

我从fb Rads获取的数据,我要转换的是这样的:

我使用我的代码得到的数据是这样的(格式没问题,但值的顺序不对,它们不是活动的值)

daroczig 给我下面的解决方案,似乎工作正常!

## 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))