【问题标题】:Splitting single column into four columns and count repeated pattern in R将单列拆分为四列并计算 R 中的重复模式
【发布时间】:2020-09-10 00:59:26
【问题描述】:

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

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

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

预期输出

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 从数据框中提取。

【问题讨论】:

  • countfrom 基于from 元素在列中重复的次数。 counttoto 元素在列中重复的次数。

标签: r string dplyr


【解决方案1】:

使用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

【讨论】:

  • 是否也可以将分组变量添加到这个rle函数中??想象前几行来自参与者 A1,其余的来自参与者 A2。我能否将此信息添加到rle 函数的输出中?
【解决方案2】:

或者在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

【讨论】:

  • 欢迎您。我发现 rleleadlapply 更容易理解。或者,天堂帮助我们,reduce
  • 这是真的,大卫。我真的很喜欢简单。在 Stackoverflow 中很难同时接受这两个答案。
  • 感谢您的帮助。是否也可以将分组变量添加到此 rle 函数?想象前几行来自参与者 A1,其余的来自参与者 A2。我能否将此信息添加到rle 函数的输出中?特别是,我想使用dplyr 管道。
  • 我想是的......但我不太确定你在问什么。我建议您将此作为一个单独的问题。提供此帖子的链接以供参考。但是请提供一个新表格来显示您正在寻找的结果。
  • 亲爱的@David T,正如您所推荐的那样。我在这里发布了一个新问题stackoverflow.com/questions/61991055/…
猜你喜欢
  • 2013-12-03
  • 1970-01-01
  • 2017-12-16
  • 2021-12-28
  • 2018-02-05
  • 1970-01-01
  • 2016-06-08
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多