2017-08-07 68 views
0

我被困在列表上进行一些操作。该列表是来自googleAnalyticsR库的ga_account_list()的输出。R:使用函数操作复杂列表的元素

下面是列表的示例(前两个元素)。我叫它ga_goals:

List of 2 
$ :List of 6 
    ..$ kind  : chr "analytics#goals" 
    ..$ username : chr "[email protected]" 
    ..$ totalResults: int 9 
    ..$ startIndex : int 1 
    ..$ itemsPerPage: int 1000 
    ..$ items  :'data.frame': 9 obs. of 15 variables: 
    .. ..$ id     : chr [1:9] "1" "2" "3" "4" ... 
    .. ..$ kind     : chr [1:9] "analytics#goal" "analytics#goal" "analytics#goal" "analytics#goal" ... 
    .. ..$ selfLink    : chr [1:9] "https://www.googleapis.com/analytics/v3/management/accounts/46324974/w 

...... 

$ :List of 6 
    ..$ kind  : chr "analytics#goals" 
    ..$ username : chr "[email protected]" 
    ..$ totalResults: int 8 
    ..$ startIndex : int 1 
    ..$ itemsPerPage: int 1000 
    ..$ items  :'data.frame': 8 obs. of 15 variables: 
    .. ..$ id     : chr [1:8] "2" "3" "4" "5" ... 
    .. ..$ kind     : chr [1:8] "analytics#goal" "analytics#goal" "analytics#goal" "analytics#goal" ... 
    .. ..$ selfLink    : chr [1:8] "https://www.googleapis.com/analytics/v3/management/accounts/46324974/w 

我想要做的是编写一个函数,删除这个列表的一些元素。例如,我想删除“kind”和“username”字段。

我试图通过编写一个可以应用到ga_goals列表的函数来利用r函数编程功能。但它没有奏效。

这里是功能和来电吧:

clean_goal_list <- function(goal_list){ 

goal_list[["kind"]] <- NULL 

} 

map(ga_goals, clean_goal_list) 

运行此returnst以下的输出:

[[1]] 
NULL 

[[2]] 
NULL 

而原始列表保持不变。

我感谢任何帮助!

+0

最后返回修改后的值:'clean_goal_list < - function(goal_list){; goal_list [[“b”]] < - NULL; goal_list; }'。 – lmo

回答

1

我终于明白自己为什么我的方法没有奏效。

我的错误是我认为我可以直接操作ga_goals作为地图函数的参数。我所知道的是在函数内部关闭这个列表的副本,并返回操作列表作为函数的输出。

我的第二个错误是尝试使用goal_list [[“kind”]]来寻址列表元素(在函数内部)。这没有奏效。我尝试了goal_list $ kind,并按预期工作。