Converting two columns of a data frame to a named vector

后端 未结 6 1084
無奈伤痛
無奈伤痛 2020-11-29 06:31

I need to convert a multi-row two-column data.frame to a named character vector. My data.frame would be something like:

dd = data.         


        
相关标签:
6条回答
  • 2020-11-29 06:45

    You can also use deframe(x) from the tibble package for this.

    tibble::deframe()
    

    It converts the first column to names and second column to values.

    0 讨论(0)
  • 2020-11-29 06:45

    There's also a magrittr solution to this via the exposition pipe (%$%):

    library(magrittr)
    
    dd %$% set_names(as.character(name), crit)
    

    Minor advantage over tibble::deframe is that one doesn't have to have exactly a two-column frame/tibble as argument (i.e., avoid a select(value_col, name_col) %>%).

    Note that the magrittr::set_names versus base::setNames is exchangeable. I simply prefer the former since it matches "set_(col|row)?names".

    0 讨论(0)
  • 2020-11-29 06:49

    For variety, try split and unlist:

    unlist(split(as.character(dd$name), dd$crit))
    #        a        b        c        d 
    #  "Alpha"   "Beta" "Caesar"  "Doris" 
    
    0 讨论(0)
  • 2020-11-29 06:52

    Here is a very general, easy way. Presently, it works with the development version of dplyr available via github

    # devtools::install_github("tidyverse/dplyr") # dplyr_0.8.99.9003
    
    # .rs.restartR() # Restart R session if dplyr was loaded before
    library(dplyr)
    
    iris %>%
      pull(Sepal.Length, Species)
    
    

    (the first argument is the values, the second argument is the names)

    0 讨论(0)
  • 2020-11-29 06:57

    Use the names function:

    whatyouwant <- as.character(dd$name)
    names(whatyouwant) <- dd$crit
    

    as.character is necessary, because data.frame and read.table turn characters into factors with default settings.

    If you want a one-liner:

    whatyouwant <- setNames(as.character(dd$name), dd$crit)
    
    0 讨论(0)
  • 2020-11-29 07:06

    You can make a vector from dd$name, and add names using names(), but you can do it all in one step with structure():

    whatiwant <- structure(as.character(dd$name), names = as.character(dd$crit))
    
    0 讨论(0)
提交回复
热议问题