【问题标题】:Extract unique value from a list of data frames into new data frame with indexing从数据帧列表中提取唯一值到带有索引的新数据帧中
【发布时间】:2017-03-02 08:38:08
【问题描述】:

我有以下结构的数据框列表:

cust_num   V2   V3 ...

每个数据框代表一组客户,其中cust_num 可以在单个数据框中出现多次。

我想提取每个数据框的unique 客户,并将它们插入到一个新的数据框,其中包含他们来自的数据框(即组)的index

这是一个例子:

# df1

cust_num   V2   V3 ...
   1 
   1
   2 

# df2

cust_num   V2   V3 ...
   4 
   4
   5 

我希望我的结果是:

cust_num   group
     1       1
     2       1
     4       2
     5       2

我尝试使用for 循环,但在将数据插入新数据框并创建组index 时遇到了麻烦:

for (i in 1:length(df_list)) {
          x <- unique(df_list[[i]][1])
          new_df <- rbind(x)
}

提前谢谢你

【问题讨论】:

  • 如果dat 是您的数据框列表:do.call(rbind,lapply(seq_along(dat), function(x) data.frame(cust_num=unique(dat[[x]][,1]),group=x)))
  • @count 您应该将其添加为答案

标签: r list unique


【解决方案1】:

如果 dat 是您的数据框列表:

do.call(rbind,lapply(seq_along(dat), function(x) data.frame(cust_num=unique(dat[[x]][,1]),group=x))) 

【讨论】:

  • 非常感谢。非常优雅。
【解决方案2】:

如果我正确理解您的问题,我认为您可以通过使用 dplyr 包将数据帧绑定在一起,同时添加 index 列来避免 for 循环。

library(dplyr)

# Bind list of data frames into a single data frame.
d1 <- bind_rows(df_list, .id = "index")

# Remove duplicates.
filter(d1, !duplicated(d1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2022-12-17
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多