简体   繁体   中英

How do I convert a data frame with two key:value columns to a list and to JSON format in R

I have a data frame that looks like this (except 10000+ rows):

      V1         V2
  google 0.99702575
   gmail 0.02492131
    maps 0.02040844
motorola 0.02006636
    view 0.01679274

I need to convert it into JSON format with toJSON(), but I first need to convert it into a list that looks like this:

$google
[1] 0.99702575

$gmail
[1] 0.2492131

$maps
[1] 0.02040844

$motorola
[1] 0.02006636

$view
[1] 0.01679274

All I would need to do at that point is toJSON(list). The end result should look like this:

{"google":0.99702575,"gmail":0.02492131,"maps":0.02040844,"motorola":0.02006636,"view":0.01679274}

How do I do it?

Create a list and set names using setNames

as.list(setNames(dat$V2,dat$V1))

Using your data, For example:

dat <- read.table(text='    V1         V2
  google 0.99702575
   gmail 0.02492131
    maps 0.02040844
motorola 0.02006636
    view 0.01679274',header=TRUE)
ll <- as.list(setNames(dat$V2,dat$V1))
library(rjson)
toJSON(ll)

Create a list, then set the names

V2 <- as.list(DF[['V2']])
names(V2) <- as.character(DF[['V1']])
# V2 is now the list you requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM