Reputation: 526
I am trying to extract and paste together elements of a list of lists generated using strsplit. For example:
cat<-c("X0831_d8_f1_2s_wt_8_ROI_009", "X0831_d8_f1_2s_wt_8_ROI_008",
"X0831_d8_f1_2s_wt_8_ROI_007", "X0831_d8_f1_2s_wt_8_ROI_006",
"X0831_d8_f1_2s_wt_8_ROI_005", "X0831_d8_f1_2s_wt_8_ROI_004",
"X0831_d8_f1_2s_wt_8_ROI_003", "X0831_d8_f1_2s_wt_8_ROI_002",
"X0831_d8_f1_2s_wt_8_ROI_001", "X0831_d8_f1_10s_wt_8_ROI_019",
"X0831_d8_f1_10s_wt_8_ROI_018")
I can generate the desired character vector using ldply:
mouse<-ldply(strsplit(cat, "_"))
paste(mouse$V4,mouse$V8,sep="_")
but was looking for a more elegant method of doing it. Perhaps using sapply or something similar?
I can generate a character vector containing one element:
sapply(strsplit(cat, "_"), "[[",4 )
but can't figure out a way to extract both elements (and paste them together).
Upvotes: 1
Views: 2037
Reputation: 24945
Your example in plyr
is pretty nice already, but here's how to do it in sapply
, using an anonymous function:
sapply(strsplit(cat, "_"), function(x){paste(x[[4]], x[[8]], sep="_")})
The apply
family, and several other functions can use anonymous functions, where you define them in the call. In this case, we have a function that takes each member of the list (as x
), and then pastes the x[[4]]
and x[[8]]
together.
Upvotes: 3