将R数据框转换为JSON

时间:2020-03-26 23:35:04

标签: r json jsonlite

嗨!我有以下格式的R数据框:

def tan_Gmix_van_Laar(x,α,β):
    if x>1 or x<0:
        print("for tan_Gmix_van_Laar: x out of bounds")
        return
    G = (x-x**2)*α*β/(β+(α-β)*x) + x*np.log(x)+(1-x)*np.log(1-x)
    m = α*β/(β+(α-β)*x)*(1-2*x) - α*β*(α-β)/((α-β)*x+β)**2*(x-x**2) + np.log(x/(1-x))
    b = G-m*x
    tanparams = np.array([m,b])
    return tanparams

如何使用所需的输出将其转换为JSON:

static const struct {
    uint8_t  type;
    uint32_t period_us; // ***  set period in  us  ***    ex 50000 = 20Hz   20000  = 50 HZ//
} sensor_list[] = {
#if USE_RAW_ACC
    { INV_SENSOR_TYPE_RAW_ACCELEROMETER, 50000 /* 20 Hz */ },
#endif
#if USE_RAW_GYR
    { INV_SENSOR_TYPE_RAW_GYROSCOPE,     50000 /* 20 Hz */ },
#endif
#if USE_CAL_ACC
    { INV_SENSOR_TYPE_ACCELEROMETER, 500000 /* 20 Hz */ },     
etc....

};

我正在使用jsonlite软件包。

1 个答案:

答案 0 :(得分:1)

使用带有嵌入式['whole milk', 'margarine'] ['yogurt', 'brown bread', 'coffee'] ['pork', 'yogurt', 'coffee'] ['bottled water', 'bottled beer'] ['whole milk'] ['salty snac'] 的列表列:

data.frame

一个区别是,在您的字典中,dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text=" user_id email segment name 123 a@gmail.com new a 234 b@gmail.com old b") dat$custom_data <- lapply(dat$segment, function(a) data.frame(segment = a)) dat$tags <- lapply(dat$name, function(a) data.frame(name = a)) dat$segment <- dat$name <- NULL jsonlite::toJSON(dat, pretty = TRUE) # [ # { # "user_id": 123, # "email": "a@gmail.com", # "custom_data": [ # { # "segment": "new" # } # ], # "tags": [ # { # "name": "a" # } # ] # }, # { # "user_id": 234, # "email": "b@gmail.com", # "custom_data": [ # { # "segment": "old" # } # ], # "tags": [ # { # "name": "b" # } # ] # } # ] 只是一个字典/哈希,而"custom_data"则将该字典放在列表中(长度为1)。

如果您是tidyverse迷(不是坏意思):

jsonlite

如果您喜欢library(dplyr) dat %>% mutate( custom_data = purrr::map(segment, ~ tibble(segment = .x)), tags = purrr::map(name, ~ tibble(name = .x)) ) %>% select(-segment, -name) %>% jsonlite::toJSON(., pretty = TRUE) ,那么

data.table

或者如果您仍然喜欢library(data.table) as.data.table(dat)[ ][, c("custom_data", "tags") := .(lapply(dat$segment, function(a) data.frame(segment = a)), lapply(dat$name, function(a) data.frame(name = a))) ][, c("segment", "name") := NULL ][, jsonlite::toJSON(.SD, pretty = TRUE) ] 的“管道式”流程,

magrittr