如何按R中列表中的唯一值进行分组

时间:2021-11-19 12:49:28

My data frame has a variable of class list (the str output gives: $ X2 :List of 125). I would like to group by unique values in this list to preform some aggregate functions, but when I use group_by in dplyr I get:

我的数据框有一个类列表变量(str输出给出:$ X2:125的列表)。我想按此列表中的唯一值进行分组以执行一些聚合函数,但是当我在dplyr中使用group_by时,我得到:

Error in eval(expr, envir, enclos) : 
  cannot group column X2, of class 'list':

A.) Is there a way to group by unique values in a list? Either using dplyr or some other grouping function? B.) Is there a way to convert the list variable to a factor variable with levels? I have no need for the variable X2 to be a list, thats just how the values were generated. But I do need to be able to group_by unique values.

A.)有没有办法按列表中的唯一值进行分组?使用dplyr还是其他一些分组功能? B.)有没有办法将列表变量转换为具有级别的因子变量?我不需要将变量X2作为列表,这就是生成值的方式。但我确实需要能够group_by唯一值。

The data frame I am using has the following structure:

我使用的数据框具有以下结构:

    'data.frame':   125 obs. of  5 variables:
 $ MOV  : int  -69 -68 -67 -63 -62 -60 -59 -56 -55 -54 ...
 $ X    : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Count: int  1 1 1 1 2 1 1 1 2 1 ...
 $ Perc : num  0.000179 0.000179 0.000179 0.000179 0.000358 ...
 $ X2   :List of 125

Any and all help would be appreciated.

任何和所有的帮助将不胜感激。

Edit: Here is the dput output:

编辑:这是输出输出:

structure(list(MOV = c(-69L, -68L, -67L, -63L, -62L, -60L), X = 1:6, 
    Count = c(1L, 1L, 1L, 1L, 2L, 1L), Perc = c(0.000178922884236894, 
    0.000178922884236894, 0.000178922884236894, 0.000178922884236894, 
    0.000357845768473788, 0.000178922884236894), X2 = structure(list(
        range = "[ -69 , -35 )", range = "[ -69 , -35 )", range = "[ -69 , -35 )", 
        range = "[ -69 , -35 )", range = "[ -69 , -35 )", range = "[ -69 , -35 )"), .Names = c("range", 
    "range", "range", "range", "range", "range"))), .Names = c("MOV", 
"X", "Count", "Perc", "X2"), row.names = c(NA, 6L), class = "data.frame")

1 个解决方案

#1


1  

As you already found out, it is not possible to group by X2 as a list using dplyr. So one way you could try is to convert to factor and then group by X2.

正如您已经发现的那样,使用dplyr无法将X2分组为列表。因此,您可以尝试的一种方法是转换为因子,然后按X2分组。

If your data.frame is called df try the following:

如果你的data.frame被调用,请尝试以下方法:

df$X2 <- as.factor(unlist(df$X2))

Afterwards you can use dplyr to group by any variable including X2

之后,您可以使用dplyr按任何变量(包括X2)进行分组

#1


1  

As you already found out, it is not possible to group by X2 as a list using dplyr. So one way you could try is to convert to factor and then group by X2.

正如您已经发现的那样,使用dplyr无法将X2分组为列表。因此,您可以尝试的一种方法是转换为因子,然后按X2分组。

If your data.frame is called df try the following:

如果你的data.frame被调用,请尝试以下方法:

df$X2 <- as.factor(unlist(df$X2))

Afterwards you can use dplyr to group by any variable including X2

之后,您可以使用dplyr按任何变量(包括X2)进行分组