合并r

时间:2017-12-01 07:03:12

标签: r list for-loop character

我有一个字符列表数据列表。数据类型和示例如下,

typeof(data)
[1] "list"


print(data[1:3])

$...
[1] ",75=20140102,268=18,"                       
[2] "0,83=337407,"  
[3] "0,83=337408,"
[4] "0,83=3374779,"               


$...
[1] ",75=20140122,268=336,"                        
[2] "3,273=143000000,1020=50,"  
[3] "1,270=422,271=1,273=143000000,"  
[4] "0,83=337427,107=ZCH4,"  
[5] "1020=58,"  

$...
[1] ",52=20140102143000085,75=20140102,268=17,"                       
[2] "0,83=33744562,107=ZCH4,"

对于列表中的每个元素,我想组合数据[[i]] [1]和其余元素。我现在正在做一个循环,它可以工作,但非常慢。 这是我的代码, 我目前的代码是:

for (j in 1:length(data)){
for (k in 2:length(data[[j]])){
table[j+k,1]<- paste0(data[[j]][1], data[[j]][k]) #record every combination
   } }

由于数据非常大,循环运行速度非常慢。

期望的结果:

 [1] ",75=20140102,268=18, 0,83=337407,"  "                       
 [2] ",75=20140102,268=18, 0,83=337408,"
 [3] ",75=20140102,268=18, 0,83=3374779,"               
 [4] ",75=20140122,268=336, 3,273=143000000,1020=50,"                        
 [5] ",75=20140122,268=336, 1,270=422,271=1,273=143000000,"  
 [6] ",75=20140122,268=336, 0,83=337427,107=ZCH4,"  
 [7] ",75=20140122,268=336, 1020=58,"  
 [8] ",52=20140102143000085,75=20140102,268=17, 0,83=33744562,107=ZCH4,"                       

非常感谢有人可以加快编程速度。

1 个答案:

答案 0 :(得分:3)

lapply(dat, function(x) paste0(x[1], x[2:length(x)]))

会更快地做到这一点。

示例:

test <- list(a = list("test", "again", "meep"), b = list("and", "again", "doot"))

> test
$a
$a[[1]]
[1] "test"

$a[[2]]
[1] "again"

$a[[3]]
[1] "meep"


$b
$b[[1]]
[1] "and"

$b[[2]]
[1] "again"

$b[[3]]
[1] "doot"

> lapply(test, function(x) paste0(x[1], x[2:length(x)]))
$a
[1] "testagain" "testmeep" 

$b
[1] "andagain" "anddoot"