将单列拆分为四列并计算R中的重复模式
本项目的目的是了解在查看对象时如何获取信息。假设一个对象有像将单列拆分为四列并计算R中的重复模式,r,string,dplyr,R,String,Dplyr,本项目的目的是了解在查看对象时如何获取信息。假设一个对象有像a,b,c,d,e和f这样的元素。一个人可能会看A,然后转到b等等。现在,我们希望描绘并理解这个人是如何在给定刺激的不同元素之间导航的。我有在一列中捕获此移动的数据,但我需要将其拆分为几列以获得导航模式。请查找下面给出的示例 我从数据帧中提取了列。现在必须根据其特点将其分为四列 a <- c( "a", "b", "b", "b", "a", "c", "a", "b", "d", "d", "d", "e", "f", "f",
a
,b
,c
,d
,e
和f
这样的元素。一个人可能会看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)
注意:我使用了
dplyr
从数据帧中提取。使用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
r或在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
库(tidyverse)
countfrom
基于from
元素在列中重复的次数countto
是列中重复to
元素的次数。欢迎使用。我发现rle
和lead
比lappy
更容易动脑。或者,上帝保佑我们,reduce
。这是真的,大卫。我真的很喜欢简单。在Stackoverflow中很难同时接受这两个答案。谢谢你的帮助。是否也可以将分组变量添加到此rle函数??假设前几行来自参与者A1,其余来自参与者A2。我能否将此信息添加到rle
功能的输出中?特别是,我想使用dplyr
管道。我想是的。。。但我不太清楚你在问什么。我建议你把这个作为一个单独的问题来写。提供此帖子的链接以供参考。但是提供一个新的表格,显示您正在寻找的结果。亲爱的@David T,按照您的建议。我在这里发布了一个新问题,是否也可以将分组变量添加到此rle函数??假设前几行来自参与者A1,其余来自参与者A2。我能否将此信息添加到rle
功能的输出中?
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