我有df看起来像这样
df = data.frame(
name = c('leo','brad','musk','mark'),
vehicle = c(2,3,3,3),
car = c(1,1,0,0),
bike = c(1,0,1,1),
bicycle = c(0,1,1,1),
lorry = c(0,1,1,0))
DF
name vehicle car bike bicycle lorry
leo 2 1 1 0 0
musk 3 1 0 1 1
mark 3 0 1 1 1
uma 3 0 1 1 0
当我使用R将上述df插入MongoDB时,JSON代码看起来像这样
{
"name" : 'leo',
"vehicle" : 2,
"car" : 1,
"bike" : 1,
"bicycle" : 1,
"lorry" : 0
}
但我希望它像这样(如列表中的列表)
{
"name" : 'leo',
"vehicle" : 2,
"Total Vehicles": [
{"car" : 1},
{"bike" : 1},
{"bicycle" : 0},
{"lorry" : 0}
]
}
在r中,我试过了
cee = df[,c(1,2)]
com = list(df[,-c(1,2)])
see = append(cee, com)
sea = list(var = df[,c(1,2)], comment = df[,-c(1,2)])
如果答案已经提供。请给我链接。三江源
答案 0 :(得分:1)
也许tidyr::nest()
会根据需要创建对象?可以使用unnest()
<强> DF1 强>
name vehicle car bike bicycle lorry
1 leo 2 1 1 0 0
2 musk 3 1 0 1 1
3 mark 3 0 1 1 1
4 uma 3 0 1 1 0
<强> DF2 强>
df2 <- df1 %>%
nest(car:lorry, .key = 'total_vehicles')
结果......
name vehicle total_vehicles
1 leo 2 1, 1, 0, 0
2 musk 3 1, 0, 1, 1
3 mark 3 0, 1, 1, 1
4 uma 3 0, 1, 1, 0
其中total_vehicles是列表列
str(df2)
'data.frame': 4 obs. of 3 variables:
$ name : Factor w/ 4 levels "leo","mark","musk",..: 1 3 2 4
$ vehicle : int 2 3 3 3
$ total_vehicles:List of 4
..$ :'data.frame': 1 obs. of 4 variables:
.. ..$ car : int 1
.. ..$ bike : int 1
.. ..$ bicycle: int 0
.. ..$ lorry : int 0
..$ :'data.frame': 1 obs. of 4 variables:
.. ..$ car : int 1
.. ..$ bike : int 0
.. ..$ bicycle: int 1
.. ..$ lorry : int 1
..$ :'data.frame': 1 obs. of 4 variables:
.. ..$ car : int 0
.. ..$ bike : int 1
.. ..$ bicycle: int 1
.. ..$ lorry : int 1
..$ :'data.frame': 1 obs. of 4 variables:
.. ..$ car : int 0
.. ..$ bike : int 1
.. ..$ bicycle: int 1
.. ..$ lorry : int 0
答案 1 :(得分:0)
df1 = df[,c('name','vehicle')]
df1$Total_Vehicles = df[,c('car','bike','bicycle','lorry')]
> df1
name vehicle Total_Vehicles.car Total_Vehicles.bike
1 leo 2 1 1
2 brad 3 1 0
3 musk 3 0 1
4 uma 3 0 1
Total_Vehicles.bicycle Total_Vehicles.lorry
1 0 0
2 1 1
3 1 1
4 1 0
> str(df1)
'data.frame': 4 obs. of 3 variables:
$ name : Factor w/ 4 levels "brad","leo","uma",..: 2 1 4 3
$ vehicle : num 2 3 3 3
$ Total_Vehicles:'data.frame': 4 obs. of 4 variables:
..$ car : num 1 1 0 0
..$ bike : num 1 0 1 1
..$ bicycle: num 0 1 1 1
..$ lorry : num 0 1 1 0
插入mongoDB JSON时的数据如下所示:
{
"_id" : ObjectId("5a4107ccff03e12bf800141c"),
"name" : "leo",
"vehicle" : 2.0,
"Total_Vehicles" : {
"car" : 1.0,
"bike" : 1.0,
"bicycle" : 0.0,
"lorry" : 0.0
}
},
{
"_id" : ObjectId("5a4107ccff03e12bf800141d"),
"name" : "brad",
"vehicle" : 3.0,
"Total_Vehicles" : {
"car" : 1.0,
"bike" : 0.0,
"bicycle" : 1.0,
"lorry" : 1.0
}
},
{
"_id" : ObjectId("5a4107ccff03e12bf800141e"),
"name" : "musk",
"vehicle" : 3.0,
"Total_Vehicles" : {
"car" : 0.0,
"bike" : 1.0,
"bicycle" : 1.0,
"lorry" : 1.0
}
},
{
"_id" : ObjectId("5a4107ccff03e12bf800141f"),
"name" : "uma",
"vehicle" : 3.0,
"Total_Vehicles" : {
"car" : 0.0,
"bike" : 1.0,
"bicycle" : 1.0,
"lorry" : 0.0
}
}