gpt4 book ai didi

r - 向量元素到数据框的不同列

转载 作者:行者123 更新时间:2023-12-04 12:30:52 25 4
gpt4 key购买 nike

我有一个 df:

   group number id
1 A abcd 1
2 A abcd 2
3 A abcd 3
4 A efgh 4
5 A efgh 5
6 B abcd 1
7 B abcd 2
8 B abcd 3
9 B abcd 9
10 B ijkl 10

我想让它像这样:
   group number  data1 data2 data3 data4           Length
1 A abcd 1 2 3 3
2 A efgh 4 5 2
3 B abcd 1 2 3 9 4
4 B ijkl 10 1

对不起,我只能像这样进入 df2:
   group number     data               Length
1 A abcd c(1,2,3) 3
2 A efgh c(4,5) 2
3 B abcd c(1,2,3,9) 4
4 B ijkl 10 1

我的代码在这里:
library(tidyverse)

df <- data.frame (group = c(rep('A',5),rep("B",5)),
number = c(rep('abcd',3),rep('efgh',2),rep('abcd',4),rep('ijkl',1)),
id = c(1,2,3,4,5,1,2,3,9,10))

df2 <- df %>%
group_by(group,number) %>%
nest() %>%
mutate(data=map(data,~unlist(.x, recursive = TRUE, use.names = FALSE)),
Length= map(data, ~length(.x)))

请随意从 df 或 df2 开始,使用(out)任何包都可以。

最佳答案

您可以更改名称 countlength (另外,我更喜欢将“空格”设置为 NA ,如果想更改它, df2[is.na(df2)]='' )

选项1

df <- data.frame (group = c(rep('A',5),rep("B",5)),
number = c(rep('abcd',3),rep('efgh',2),rep('abcd',4),rep('ijkl',1)),
id = c(1,2,3,4,5,1,2,3,9,10))

df2 <- df %>%
group_by(group,number) %>%
mutate(data=toString(id),count=n())

library(splitstackshape)
cSplit(df2, 3, drop = TRUE,sep=',')


group number count data_1 data_2 data_3 data_4
1: A abcd 3 1 2 3 NA
2: A efgh 2 4 5 NA NA
3: B abcd 4 1 2 3 9
4: B ijkl 1 10 NA NA NA

选项 2
library(dplyr)
library(tidyr)

df2 <- df %>%
group_by(group,number) %>%
summarise(data=toString(id),count=n())%>%separate_rows(data)%>% mutate(Col = paste0("data", 1:n()))%>%spread(Col, data)
df2
# A tibble: 4 x 8
# Groups: group [2]
group number count data1 data2 data3 data4 data5
* <fctr> <fctr> <int> <chr> <chr> <chr> <chr> <chr>
1 A abcd 3 1 2 3 <NA> <NA>
2 A efgh 2 <NA> <NA> <NA> 4 5
3 B abcd 4 1 2 3 9 <NA>
4 B ijkl 1 <NA> <NA> <NA> <NA> 10

关于r - 向量元素到数据框的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46228293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com