我有列表(元素数量不均匀):
my.list = list(col1 = c("CC", "CT", "TT"),
col2 = c("GG", "GT"),
col3 = c("CC", "CT"),
col4 = c("CC", "CG", "GG"),
col5 = c("AC", "CC"),
col6 = "GG")
$col1
[1] "CC" "CT" "TT"
$col2
[1] "GG" "GT"
$col3
[1] "CC" "CT"
$col4
[1] "CC" "CG" "GG"
$col5
[1] "AC" "CC"
$col6
[1] "GG"
可以将其转换为数据框:
mylist.df = plyr::ldply(my.list, rbind)
names(mylist.df) <- c("cols","g1", "g2", "g3")
我想使用mylist
or对下面的数据框进行子集化mylist.df
。基本上,我想保留每个值至少有一个元素的每一行mylist
:
df.to.subset = structure(list(IDs = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6"),
gr = c("gr1", "gr1", "gr1", "gr1", "gr1", "gr1"),
var = c(-3.451, -3.469, -3.837, -3.344, -3.904, -3.943),
col1 = structure(c(1L, 2L, 3L, 1L, 2L, 2L), levels = c("CC", "CT", "TT"), class = "factor"),
col2 = structure(c(1L, 1L, 2L, 3L, 3L, 3L), levels = c("GG", "GT", "TT"), class = "factor"),
col3 = structure(c(1L, 2L, 1L, 1L, 1L, 1L), levels = c("CC", "CT"), class = "factor"),
col4 = structure(c(2L, 2L, 2L, 2L, 2L, 2L), levels = c("CC", "CG", "GG"), class = "factor"),
col5 = structure(c(1L, 2L, 2L, 2L, 2L, 2L), levels = c("AC", "CC"), class = "factor"),
col6 = structure(c(1L, 1L, 2L, 1L, 1L, 1L), levels = c("GG","AA"), class = "factor")),
row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
IDs gr var col1 col2 col3 col4 col5 col6
<chr> <chr> <dbl> <fct> <fct> <fct> <fct> <fct> <fct>
1 ID1 gr1 -3.45 CC GG CC CG AC GG
2 ID2 gr1 -3.47 CT GG CT CG CC GG
3 ID3 gr1 -3.84 TT GT CC CG CC AA
4 ID4 gr1 -3.34 CC TT CC CG CC GG
5 ID5 gr1 -3.90 CT TT CC CG CC GG
6 ID6 gr1 -3.94 CT TT CC CG CC GG
(最终结果将是)
IDs gr var col1 col2 col3 col4 col5 col6
ID1 gr1 -3.45 CC GG CC CG AC GG
ID2 gr1 -3.47 CT GG CT CG CC GG
另外,我想重新调整每一列的级别以df.to.subset
匹配此数据框中的级别:
factor.levels.cols = structure(list(cols = c("col1", "col2", "col3", "col4", "col5", "col6"),
g1 = c("CC", "GG", "CC", "CC", "AA", "AA"),
g2 = c("CT", "GT", "CT", "CG", "AC", "AG"),
g3 = c("TT", "TT", "TT", "GG", "CC", "GG")),
row.names = c(NA, 6L), class = "data.frame")
cols g1 g2 g3
1 col1 CC CT TT
2 col2 GG GT TT
3 col3 CC CT TT
4 col4 CC CG GG
5 col5 AA AC CC
6 col6 AA AG GG
这里是否强制使用 for 循环,或者有没有办法让它更快?我有超过 1,000,000 个条目需要修改。