简体   繁体   English

R:用两个元素折叠向量

[英]R: collapse a vector by two elements

I have a vector, eg sdata = c('a', 'b', 'c', 'd') .我有一个向量,例如sdata = c('a', 'b', 'c', 'd')

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

How can I collapse it by two (or more if needed) elements to get the following output?我如何通过两个(或更多,如果需要)元素折叠它以获得以下 output?

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

Thanks!谢谢!

EDIT: real sample data:编辑:真实样本数据:

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"     

We can remove the last and first element of 'sdata' and paste the vectors with the same length.我们可以删除“sdata”的最后一个和第一个元素并paste具有相同长度的向量。

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

This can be also written as这也可以写成

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

Update更新

Based on the new 'sdata' (in a list ), we use lapply to loop over the list elements and use the same code基于新的“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"  

Or without using anonymous function we can paste with Map after removing the first and last list elements in the sdata或者不使用匿名 function 我们可以在删除sdata中的第一个和最后一个list元素后paste Map

  Map(paste, lapply(sdata, head, -1), lapply(sdata, tail, -1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM