给定标量和JSON表格数据来构建数据框?

时间:2018-07-26 08:18:13

标签: r dataframe

考虑我拥有的ID:

id <- 1

和带有列的JSON文件(此处转换为fromJSON的结果):

fromJSON(j$sensorsData)
                [,1]      [,2]     [,3]     [,4]      [,5]      [,6]      [,7]          [,8]          [,9]         [,10]
   [1,] 6.924485e+14 3.2289276 5.886124 7.571915 -1.000000 -1.000000 -1.000000 -1.0000000000 -1.0000000000 -1.0000000000
   [2,] 6.924485e+14 3.2313232 6.016602 7.492905 -1.000000 -1.000000 -1.000000 -1.0000000000 -1.0000000000 -1.0000000000
   [3,] 6.924485e+14 3.1798400 6.029770 7.270248 -1.000000 -1.000000 -1.000000 -1.0000000000 -1.0000000000 -1.0000000000
   [4,] 6.924485e+14 3.1882324 6.001038 7.260666 -1.000000 -1.000000 -1.000000 -1.0000000000 -1.0000000000 -1.0000000000

现在,我想创建一个数据框,其中包含我上面的矩阵的第一列ID和“ bind_cols”,并为列指定名称,例如“ col1”至“ col10”。

我正在尝试

set_names(data_frame(uuid, as_data_frame(fromJSON(j$sensorsData))), 
                            nm = c("id", "timestamp", 
                                   "acc_x", "acc_y", "acc_z", 
                                   "grav_x", "grav_y", "grav_z", 
                                   "gyro_x", "gyro_y", "gyro_z"))

但是它没有给我想要的结果:

id col1          col2       .... to col10
1  6.924485e+14  3.2289276          -1.0000000000
1  6.924485e+14  3.2313232          -1.0000000000  
1  6.924485e+14  3.1798400          -1.0000000000 

2 个答案:

答案 0 :(得分:1)

尝试一下

names <- c("id", "timestamp", 
  "acc_x", "acc_y", "acc_z", 
  "grav_x", "grav_y", "grav_z", 
  "gyro_x", "gyro_y", "gyro_z")

df <- cbind(id=1, fromJSON(j$sensorsData)); colnames(df) <- names

答案 1 :(得分:1)

如果您使用tibble软件包,只需将data_frame替换为add_column

set_names(add_column(uuid=id, as_data_frame(fromJSON(j$sensorsData))), 
                        nm = c("id", "timestamp", 
                               "acc_x", "acc_y", "acc_z", 
                               "grav_x", "grav_y", "grav_z", 
                               "gyro_x", "gyro_y", "gyro_z"))

如果您使用dplyr软件包:

set_names(dplyr::bind_cols(uuid=rep(id,nrow(as_data_frame(fromJSON(j$sensorsData)))), as_data_frame(fromJSON(j$sensorsData))), 
      nm = c("id", "timestamp", 
             "acc_x", "acc_y", "acc_z", 
             "grav_x", "grav_y", "grav_z", 
             "gyro_x", "gyro_y", "gyro_z"))