Reputation: 309
I have a list of a character list data. The type of data and example is as follows,
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,"
for each element in the list,i want to combine data[[i]][1] and the rest of its elements. I am doing it with a loop now, it works, but very slow. Here is my code, My current code is:
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
} }
Since the data is pretty large, the loop runs very slow.
Desired results:
[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,"
Thank you so much if someone can speed up the programming.
Upvotes: 2
Views: 3359
Reputation: 6685
lapply(dat, function(x) paste0(x[1], x[2:length(x)]))
will do that quicker.
Example:
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"
Upvotes: 3