【问题标题】:Using group_split on list of lists in R在 R 中的列表列表上使用 group_split
【发布时间】:2020-05-27 01:19:07
【问题描述】:

我正在尝试在列表/数据框列表上使用 group_split()。

这是我的代码。 df 是我所拥有的,而 final_df 是我想要达到的。名字可以乱扔。我的目标是为 a & b 的独特组合获得单行。

df <- data.frame(a = c(rep(68,8),rep(70,8)), b = c((1:4),(1:4),(1:4),(1:4)),c = c(rep("Mike",4),rep("Joe",4),rep("Mike",4),rep("Joe",4)), d=c(70,71,75,79,72,69,66,90,70,77,74,72,72,69,66,90), e=c(30,32,44,42,22,23,24,21,30,37,41,42,21,22,24,20))

final_df <- data.frame(a=c(rep(68,4),rep(70,4)), b=c((1:4),(1:4)), d_1 = c(70,71,75,79,70,77,74,72), e_1 = c(30,32,44,42,30,37,41,42), d_2 = c(72,69,66,90,72,69,66,90), e_2 = c(22 ,23,24,21,21,22,24,20))


print(df)
a b    c  d  e
1  68 1 Mike 70 30
2  68 2 Mike 71 32
3  68 3 Mike 75 44
4  68 4 Mike 79 42
5  68 1  Joe 72 22
6  68 2  Joe 69 23
7  68 3  Joe 66 24
8  68 4  Joe 90 21
9  70 1 Mike 70 30
10 70 2 Mike 77 37
11 70 3 Mike 74 41
12 70 4 Mike 72 42
13 70 1  Joe 72 21
14 70 2  Joe 69 22
15 70 3  Joe 66 24
16 70 4  Joe 90 20

print(final_df)

   a b d_1 e_1 d_2 e_2
1 68 1  70  30  72  22
2 68 2  71  32  69  23
3 68 3  75  44  66  24
4 68 4  79  42  90  21
5 70 1  70  30  72  21
6 70 2  77  37  69  22
7 70 3  74  41  66  24
8 70 4  72  42  90  20

最初,我使用 lapply

list <- df %>% group_split(a)

然后我认为我需要为 b 做同样的事情,但我似乎无法让 group_split 再次工作。我写了一个函数来在列表列表中应用 group_split

func <- function(y){lapply(y, y %>% group_split(b))}
list_2 <- lapply(list,function(x){lapply(x,func)})

但这不起作用。我收到此错误

Error in UseMethod("group_split") : 
  no applicable method for 'group_split' applied to an object of class "c('double', 'numeric')"

我非常感谢任何帮助。我可能会以完全错误和迂回的方式来解决这个问题。再次感谢

【问题讨论】:

    标签: r list dataframe tidyverse lapply


    【解决方案1】:

    我对此进行了尝试,但最终找到了nghauranR noob 提供的类似问题的解决方案: Combine duplicate rows in dataframe and create new columns

    应用于您的数据:

    df <- data.frame(a = c(rep(68,8),rep(70,8)), 
    b = c((1:4),(1:4),(1:4),(1:4)),
    c = c(rep("Mike",4),rep("Joe",4),rep("Mike",4),rep("Joe",4)),
    d = c(70,71,75,79,72,69,66,90,70,77,74,72,72,69,66,90), 
    e = c(30,32,44,42,22,23,24,21,30,37,41,42,21,22,24,20))
    
    library(dplyr)
    df <- df %>%
      group_by(a, b) %>%
      summarise_all(funs(paste((.), collapse = ",")))
    
    library(splitstackshape)
    df <- cSplit(df, c("c","d", "e"), ",")
    
    df <- df[,c(1,2,5,7,6,8)] #This is not strictly necessary but indexes
    # precisely your desired output
    
    > df
        a b d_1 e_1 d_2 e_2
    1: 68 1  70  30  72  22
    2: 68 2  71  32  69  23
    3: 68 3  75  44  66  24
    4: 68 4  79  42  90  21
    5: 70 1  70  30  72  21
    6: 70 2  77  37  69  22
    7: 70 3  74  41  66  24
    8: 70 4  72  42  90  20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2021-08-17
      • 2019-12-08
      • 2020-09-21
      • 2015-05-30
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多