1

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).

Damian
  • 516
  • 1
  • 4
  • 20
  • Check out [grep](https://stat.ethz.ch/R-manual/R-devel/library/base/html/grep.html), specifically `regexpr` and `gregexpr`, they will give you the first instance and the position of all instances respectively. This in conjunction with `substr` is how I do much of this type of work – Badger Sep 15 '15 at 20:18
  • if the first string always ends with `s`, you could `gsub(".*_(\\d+s)_.*_(\\d+$)", "\\1_\\2", cat)` – Rorschach Sep 15 '15 at 20:35

1 Answers1

3

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.

Jaap
  • 81,064
  • 34
  • 182
  • 193
jeremycg
  • 24,657
  • 5
  • 63
  • 74