简体   繁体   中英

Creating New Columns for List Columns in R

I have a json code below and I tried to convert it to data.frame but the first column end up being a list of other data frames.

library(jsonlite)

json_emp<-' [ {"employee": [
{
  "name": "person1",
  "ID": 1
},
  {
  "name": "person2",
  "ID": 2
  },
  {
  "name": "person3",
  "ID": 3
  }
  ],
  "date": "11-24-2015"
  },
  {
  "employee": [
  {
  "name": "person1",
  "ID": 1
  },
  {
  "name": "person2",
  "ID": 2
  }
  ],
  "date": "11-25-2015"
  },
  {
  "employee": [
  {
  "name": "person1",
  "ID": 1
  }
  ],
  "date": "11-26-2015"
  }
  ]'


df<- fromJSON(json_emp)

do.call("rbind",df$employee)

I did the do.call function and the result is like this:

        date    name ID
1 11-24-2015 person1  1
2 11-24-2015 person2  2
3 11-24-2015 person3  3
4 11-25-2015 person1  1
5 11-25-2015 person2  2
6 11-26-2015 person1  1

The result looks good but what I also need is to insert/connect the column that contains the date on the df dataframe. Is there a way to combine the two data frame or just a code that we can also include the data?

You can try using unnest from the "tidyr" package:

library(tidyr)
unnest(fromJSON(json_emp), employee)
# Source: local data frame [6 x 3]
# 
#         date    name    ID
#        (chr)   (chr) (int)
# 1 11-24-2015 person1     1
# 2 11-24-2015 person2     2
# 3 11-24-2015 person3     3
# 4 11-25-2015 person1     1
# 5 11-25-2015 person2     2
# 6 11-26-2015 person1     1

In base R, you can try (starting from your "df" step):

cbind(do.call(rbind, df$employee), 
      date = rep(df$date, sapply(df$employee, nrow)))

We could use rbindlist from library(data.table)

library(data.table)#v1.9.6+
rbindlist(with(df, setNames(employee,date)), idcol=TRUE)
#          .id    name ID
#1: 11-24-2015 person1  1
#2: 11-24-2015 person2  2
#3: 11-24-2015 person3  3
#4: 11-25-2015 person1  1
#5: 11-25-2015 person2  2
#6: 11-26-2015 person1  1

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