1

I have a list I created through a process that looks like this (so that I could pull from tidycensus):

dv_acs = c(
  hus          = "B25002_001", 
  husocc       = "B25002_002", 
  husvac       = "B17001_002"
)

I want to know if I can turn that into a data.frame. When I try to ask it to be a data.frame by:

out <- data.frame(dv_acs)

Then I get this:

           dv_acs
hus    B25002_001
husocc B25002_002
husvac B17001_002

Where the lefthand names replace what is normally 1:n but is not, in itself, a column of variables (data is noted as 3 obs of 1 variable).

tchoup
  • 971
  • 4
  • 11
  • Based on the subjects of the purported duplicates they all refer to lists but this question is about a named character vector even though it incorrectly calls it a list. – G. Grothendieck Nov 01 '22 at 15:03
  • @G.Grothendieck I kept that in mind while browsing, but they should all have answers that work for a vector as well as a list, including the ones in your answer. Feel free to edit if that's not the case for any of the links – camille Nov 01 '22 at 15:15
  • If the answer to a different question happens to be an answer that works that does not make it a duplicate. – G. Grothendieck Nov 01 '22 at 15:21
  • @G.Grothendieck one is specifically about a vector, the others are about unnested lists that will operate the same as a vector for this task. If you want to remove the list-specific ones that's fine – camille Nov 01 '22 at 15:29

2 Answers2

4

1) This uses only base R.

stack(dv_acs)
##       values    ind
## 1 B25002_001    hus
## 2 B25002_002 husocc
## 3 B17001_002 husvac

2) We can also use enframe

library(tibble)

enframe(dv_acs)
## # A tibble: 3 × 2
##   name   value     
##  <chr>  <chr>     
##  1 hus    B25002_001
##  2 husocc B25002_002
##  3 husvac B17001_002
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
3

This seems to be a named character vector, not a list as understood in R. In any case, with the data you provided, one can create a data frame by doing:

data.frame(name = names(dv_acs), dv_acs = unname(dv_acs))
#>     name     dv_acs
#> 1    hus B25002_001
#> 2 husocc B25002_002
#> 3 husvac B17001_002

Or

tibble::rownames_to_column(as.data.frame(dv_acs), 'name')
#>     name     dv_acs
#> 1    hus B25002_001
#> 2 husocc B25002_002
#> 3 husvac B17001_002
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87