[英]R - construct sparse matrix from list of lists
Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. 使用python和pandas,我可以轻松地从字典对象列表中构造一个稀疏的DataFrame。 The following code snippet shows how this can be done in pandas:
以下代码段显示了如何在熊猫中完成此操作:
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
{'b':1, 'd': 4}])
.fillna(0))
Out[1]:
a b c d
0 1.0 10.0 0.0 0.0
1 0.0 0.0 1.0 99.0
2 0.0 1.0 0.0 4.0
What if I want to easily reproduce this behavior in R? 如果我想轻松地在R中重现此行为怎么办? Let's suppose that I have the following variable:
假设我有以下变量:
values <- list(list(a = 1, b = 10),
list(d = 99, c = 1),
list(b = 1, d = 4))
Then, how the same result achieved in python can be obtained using R? 然后,如何使用R获得在python中获得的相同结果?
We can use melt
with xtabs
in R
我们可以在
R
xtabs
中使用melt
library(reshape2)
xtabs(value~L1 + L2, melt(values))
# L2
#L1 a b c d
# 1 1 10 0 0
# 2 0 0 1 99
# 3 0 1 0 4
With dplyr
you could do it like this: 使用
dplyr
您可以这样操作:
library(dplyr)
values %>% bind_rows() %>% mutate_all(function(x) coalesce(x, 0))
# A tibble: 3 × 4
a b d c
<dbl> <dbl> <dbl> <dbl>
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
Here's a solution with plyr
package: 这是使用
plyr
软件包的解决方案:
ldply(values, data.frame)
a b d c
1 1 10 NA NA
2 NA NA 99 1
3 NA 1 4 NA
# mutate each to replace NA with 0
ldply(values, data.frame) %>%
mutate_each(funs(replace(., is.na(.), 0)))
a b d c
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
Using base R to construct a matrix, you could do the following. 使用基数R构造矩阵,您可以执行以下操作。
first, the set up 首先,设置
# flatten list to pull out info for matrix construction
flat <- unlist(values)
# build a 0 matrix with correct dimensions and column names
myMat <- matrix(0, nrow=length(values), ncol=length(unique(names(flat))),
dimnames=list(NULL, sort(unique(names(flat)))))
Now, fill in the matrix 现在,填写矩阵
for(i in seq_along(values)) myMat[i, names(values[[i]])] <- unlist(values[[i]])
This results in 这导致
myMat
a b c d
[1,] 1 10 0 0
[2,] 0 0 1 99
[3,] 0 1 0 4
If you actually wanted a data.frame, you can convert the matrix with the as.data.frame
or data.frame
functions. 如果您确实需要data.frame,则可以使用
as.data.frame
或data.frame
函数转换矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.