Converting two columns of a data frame to a named

2019-02-07 18:09发布

问题:

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.frame(crit = c("a","b","c","d"), 
                name = c("Alpha", "Beta", "Caesar", "Doris")
                )

and what I actually need would be:

whatiwant = c("a" = "Alpha",
              "b" = "Beta",
              "c" = "Caesar",
              "d" = "Doris")

回答1:

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)


回答2:

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


回答3:

For variety, try split and unlist:

unlist(split(as.character(dd$name), dd$crit))
#        a        b        c        d 
#  "Alpha"   "Beta" "Caesar"  "Doris"