我有一個資料框,其中包括:一列具有單獨的 ID(唯一),第二列顯示一個常見的唯一變數。也就是說,第 1 列中的每個人都采取了相同的行動,如 B 列所示。
我想在 R 中撰寫代碼來創建新行,根據 B 列將 A 列中的每個人配對。
也就是說,給定這個例子:
person<-c("a", "b", "c", "d", "e", "f")
action<-c("x", "x", "x", "y", "y", "y")
data.frame(person, action)
我想創建這個:
person1<-c("a", "a","b", "d", "d", "e")
person2<-c("b", "c", "c", "e", "f","f")
data.frame(person1, person2)
uj5u.com熱心網友回復:
使用group_modify()and的方法combn():
library(dplyr)
df %>%
group_by(action) %>%
group_modify(~ as_tibble(t(combn(pull(.x, person), 2))))
# A tibble: 6 × 3
# Groups: action [2]
action V1 V2
<chr> <chr> <chr>
1 x a b
2 x a c
3 x b c
4 y d e
5 y d f
6 y e f
uj5u.com熱心網友回復:
這個怎么樣:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
#> Warning: package 'tidyr' was built under R version 4.1.2
person<-c("a", "b", "c", "d", "e", "f")
action<-c("x", "x", "x", "y", "y", "y")
dat <- data.frame(person, action)
dat %>%
group_by(action) %>%
summarise(person = as.data.frame(t(combn(person, 2)))) %>%
unnest(person) %>%
rename(person1=V1, person2=V2)
#> `summarise()` has grouped output by 'action'. You can override using the
#> `.groups` argument.
#> # A tibble: 6 × 3
#> # Groups: action [2]
#> action person1 person2
#> <chr> <chr> <chr>
#> 1 x a b
#> 2 x a c
#> 3 x b c
#> 4 y d e
#> 5 y d f
#> 6 y e f
由reprex 包于 2022-04-21 創建(v2.0.1)
uj5u.com熱心網友回復:
這是base R中的一個襯里。
person <- c("a", "b", "c", "d", "e", "f")
action <- c("x", "x", "x", "y", "y", "y")
df <- data.frame(person, action)
setNames(
do.call(
rbind,
lapply(split(df, df$action),
function(x) as.data.frame(t(combn(x$person, 2))))),
c("person1", "person2"))
# person1 person2
# x.1 a b
# x.2 a c
# x.3 b c
# y.1 d e
# y.2 d f
# y.3 e f
uj5u.com熱心網友回復:
使用base R
subset(merge(dat, dat, by = 'action'), person.x != person.y &
duplicated(paste(pmin(person.x, person.y), pmax(person.x, person.y))))
action person.x person.y
4 x b a
7 x c a
8 x c b
13 y e d
16 y f d
17 y f e
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460985.html
標籤:r
上一篇:根據時間戳之間的差異求和
下一篇:過濾資料,但每個ID至少保留一行
