Converting two columns of a data frame to a named vector

你离开我真会死。 提交于 2019-11-28 08:00:32

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)

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

For variety, try split and unlist:

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

You can also use for this.

tibble::deframe()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!