繁体   English   中英

将单列拆分为四列并计算 R 中的重复模式

[英]Splitting single column into four columns and count repeated pattern in R

该项目的目的是了解如何在查看 object 时获取信息。 想象一个 object 有像a , b , c , d , ef这样的元素。 一个人可能会看着a并移动到b等等。 现在,我们希望 plot 并了解该人如何在给定刺激的不同元素中导航。 我有在单个列中捕获此运动的数据,但我需要将其拆分为几列以获得导航模式。 请找到下面给出的示例。

我从数据框中提取了列。 现在必须根据其特性将其拆分为四列。

a <- c( "a", "b", "b", "b", "a", "c", "a", "b", "d", "d", "d", "e", "f", "f", "e", "e", "f")
a <- as.data.frame(a)

预期 output

from   to   countfrom   countto

a      b      1           3
b      a      3           1
a      c      1           1
c      a      1           1
a      b      1           1
b      d      1           3
d      e      3           1      
e      f      1           2
f      e      2           2
e      f      2           1 

注意:我使用dplyr从 dataframe 中提取。

使用rle获取每个字母的相对运行,然后将其拼凑在一起:

r <- rle(a$a)
## or maybe `r <- rle(as.character(a$a)` depending on your R version
setNames(
    data.frame(lapply(r, head, -1), lapply(r, tail, -1)),
    c("countfrom","from","countto","to")
)
##   countfrom from countto to
##1          1    a       3  b
##2          3    b       1  a
##3          1    a       1  c
##4          1    c       1  a
##5          1    a       1  b
##6          1    b       3  d
##7          3    d       1  e
##8          1    e       2  f
##9          2    f       2  e
##10         2    e       1  f

或者在tidyverse中

library(tidyverse)
a <- c( "a", "b", "b", "b", "a", "c", "a", "b", "d", 
        "d", "d", "e", "f", "f", "e", "e", "f")
foo <- rle(a)

answ <- tibble(from = foo$values, to = lead(foo$values),
               fromCount = foo$lengths, toCount = lead(foo$lengths)) %>% 
  filter(!is.na(to))


# A tibble: 10 x 4
   from  to    fromCount toCount
   <chr> <chr>     <int>   <int>
 1 a     b             1       3
 2 b     a             3       1
 3 a     c             1       1
 4 c     a             1       1
 5 a     b             1       1
 6 b     d             1       3
 7 d     e             3       1
 8 e     f             1       2
 9 f     e             2       2
10 e     f             2       1

暂无
暂无

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

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