简体   繁体   English

从向量列表的元素中提取向量

[英]Extract vectors from elements of list of vectors

I have some json data [{a:10, b:123,c:4.5},{a:2,b:5,c:33}] and so on that I read into R via json_data <- fromJSON(paste(json_file, collapse="")) (json_file is the input url). 我有一些json数据[{a:10, b:123,c:4.5},{a:2,b:5,c:33}]等等,我通过json_data <- fromJSON(paste(json_file, collapse=""))读取R json_data <- fromJSON(paste(json_file, collapse="")) (json_file是输入url)。 So far so fine. 到目前为止很好。 Now I would like to create vectors from this input which fromJSON has converted into a List of vectors where the vectors have components a,b,c. 现在我想从这个输入创建向量,从fromJSON转换为向量列表,其中向量具有组件a,b,c。

Is there a better way than looping over the input list and doing this manually by concatenating the individual vector components on the new target vector(s)? 有没有比循环输入列表更好的方法,并通过连接新目标矢量上的各个矢量组件手动执行此操作?

If you have a list like this: 如果您有这样的列表:

l <- list(c(a=10, b=123, c=4.5),c(a=2,b=5,c=33))

You could just do something like the following: 您可以执行以下操作:

df <- data.frame(do.call(rbind, l))
#    a   b    c
# 1 10 123  4.5
# 2  2   5 33.0
as.list(df)
# $a
# [1] 10  2
# $b
# [1] 123   5
# $c
# [1]  4.5 33.0

(The do.call(rbind, X) construct is handy, allowing you to rbind together the elements of a list of arbitrary length. You can then slice and dice the resulting matrix as you see fit --- I just converted it to a data.frame and then to a list to show a couple of possibilities.) (该do.call(rbind, X)结构是得心应手,让您rbind在一起的任意长度的列表中的元素。然后,您可以切片和切块所产生的矩阵,你认为合适---我只是把它转换成data.frame然后到list以显示几种可能性。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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