2016-08-22 96 views
-1

重叠对所以我获得来自特征向量

xx = c("AAA", "ABC", "CBS") 
xx 
length(nchar(xx)) 

我试图让我的每个字符串中的向量对二分裂了这一点,以下特征向量。在上面的例子中,它会看起来像一个数据帧,其中:

AAA ABC 
ABC CBS 

我一直在试图避免环路我的数据会很大。

split(xx, 2) 
split(xx, cut(seq_along(xx), 2, labels = FALSE)) 
split(xx, cut(seq_along(xx), 2, labels = FALSE))[[1]] 
split(xx, cut(seq_along(xx[-1]), 2, labels = FALSE))[[1]] 

对避免for循环的解决方案的任何建议。

随着五个条目:

xx = c("AAA", "ABC", "CBS", "BBB", "GGG") 
xx 

AAA ABC 
ABC CBS 
CBS BBB 
BBB GGG 
+0

它应该是xx [1]和xx [2]。然后xx [2]和xx [3]。这是事件的顺序,所以在这种情况下不需要xx [1]和xx [3]。 – AGUY

+0

那么,如果我们扩展到'xx'有5个条目应该如何? – bouncyball

+1

'embed(xx,2)[,2:1]'? – Frank

回答

1

随着dplyrtidyr

xx = c("AAA", "ABC", "CBS", "BBB", "GGG") 

library(dplyr) 
df <- data.frame(col1 = xx) %>% 
    mutate(col2 = lead(col1)) %>% 
    tidyr::drop_na() 

输出

# col1 col2 
# 1 AAA ABC 
# 2 ABC CBS 
# 3 CBS BBB 
# 4 BBB GGG 
1

我们可以使用data.table

library(data.table) 
na.omit(as.data.table(xx)[, xx1 := shift(xx, type = "lead")]) 
# xx xx1 
#1: AAA ABC 
#2: ABC CBS 
#3: CBS BBB 
#4: BBB GGG