R:用两个元素折叠一个向量

R: collapse a vector by two elements

我有一个向量,例如sdata = c('a', 'b', 'c', 'd')

sdata
[1] "a" "b" "c" "d"

如何通过两个(或更多,如果需要)元素折叠它以获得以下输出?

desiredOutput 
[1] "a b" "b c" "c d"

谢谢!

编辑:真实样本数据:

sdata = list(c("salmon", "flt", "atl", "farm", "wild", "per", "lb", "or", 
"fam", "pk"), c("vit", "min", "adult", "eye", "visit", "our", 
"pharmacy", "we", "accept", "express", "script", "offer", "val", 
"mathing", "pricing", "fast", "conv", "service"), c("ct", "gal", 
"or", "drawstring", "odor", "shield", "twist", "tie", "lawn", 
"leaf", "in", "plumber", "brush"))

 sdata
[[1]]
 [1] "salmon" "flt"    "atl"    "farm"   "wild"   "per"    "lb"     "or"     "fam"    "pk"    

[[2]]
 [1] "vit"      "min"      "adult"    "eye"      "visit"    "our"      "pharmacy" "we"       "accept"   "express"  "script"  
[12] "offer"    "val"      "mathing"  "pricing"  "fast"     "conv"     "service" 

[[3]]
 [1] "ct"         "gal"        "or"         "drawstring" "odor"       "shield"     "twist"      "tie"        "lawn"      
[10] "leaf"       "in"         "plumber"    "brush"     

我们可以删除'sdata'和paste长度相同的向量的最后一个和第一个元素。

 paste(sdata[-length(sdata)], sdata[-1])
 #[1] "a b" "b c" "c d"

这也可以写成

 paste(head(sdata,-1), tail(sdata,-1))
 #[1] "a b" "b c" "c d"

更新

基于新的'sdata'(在list中),我们使用lapply遍历list元素并使用相同的代码

lapply(sdata, function(x) paste(head(x,-1), tail(x,-1)))
#[[1]]
#[1] "salmon flt" "flt atl"    "atl farm"   "farm wild"  "wild per"  
#[6] "per lb"     "lb or"      "or fam"     "fam pk"    

#[[2]]
# [1] "vit min"         "min adult"       "adult eye"       "eye visit"      
# [5] "visit our"       "our pharmacy"    "pharmacy we"     "we accept"      
# [9] "accept express"  "express script"  "script offer"    "offer val"      
#[13] "val mathing"     "mathing pricing" "pricing fast"    "fast conv"      
#[17] "conv service"   

#[[3]]
# [1] "ct gal"          "gal or"          "or drawstring"   "drawstring odor"
# [5] "odor shield"     "shield twist"    "twist tie"       "tie lawn"       
# [9] "lawn leaf"       "leaf in"         "in plumber"      "plumber brush"  

或者在不使用匿名函数的情况下,我们可以在删除 sdata

中的第一个和最后一个 list 元素后使用 Map paste
  Map(paste, lapply(sdata, head, -1), lapply(sdata, tail, -1))