首页 > 解决方案 > Remove columns from data.frame that are of type list

问题描述

Given a data.frame that has list columns and trying to write it to a csv file, how can a user drop all columns of type list?

dput would be quite long. See an example here Note that full df has 5+ list columns and I prefer not enumerating them or hunting them by name.

> str(df,max.level=1)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   2237 obs. of  30 variables:
 $ CATEGORY    : chr  "ARTICLE " "ARTICLE " "ARTICLE " "ARTICLE " ...
 $ BIBTEXKEY   : chr  "RN69" "RN4023" "RN3332" "RN58" ...
 $ ADDRESS     : chr  NA NA NA NA ...
 $ ANNOTE      : chr  NA NA NA NA ...
 $ AUTHOR      :List of 2237
 $ BOOKTITLE   : chr  NA NA NA NA ...
 and 40+ other columns

> names(df)
 [1] "CATEGORY"     "BIBTEXKEY"    "ADDRESS"      "ANNOTE"       "AUTHOR"       "BOOKTITLE"   
 [7] "CHAPTER"      "CROSSREF"     "EDITION"      "EDITOR"       "HOWPUBLISHED" "INSTITUTION" 
[13] "JOURNAL"      "KEY"          "MONTH"        "NOTE"         "NUMBER"       "ORGANIZATION"
[19] "PAGES"        "PUBLISHER"    "SCHOOL"       "SERIES"       "TITLE"        "TYPE"        
[25] "VOLUME"       "YEAR"         "ISSN"         "DOI"          "ISBN"         "URL"         
> 

the command should looke something like

df %>% select_if(!is.list) but it is not fully correct

df comes from

devtools::install_github("ropensci/bib2df")
library(bib2df)
url <- "https://cprd.com/bibliography/export/bibtex"
df <- bib2df(url)

this selects them correctly but negation seems hard to do

df %>% select_if(is_list)

标签: rlistdataframesubset

解决方案


给定

dat <- tibble::tibble(a = 1,
                      b = list(d = c(1, 2)))

我们可以用

Filter(Negate(is.list), dat)

要得到

# A tibble: 1 x 1
#      a
#  <dbl>
#1     1

输入Negate控制台,我们会看到它的作用

function (f) 
{
    f <- match.fun(f)
    function(...) !f(...)
}

推荐阅读