首页 > 解决方案 > 计算数据帧列表中的出现次数并将结果存储在 R 中的新数据帧中

问题描述

我有一个大约 80 个数据框的列表,格式如下:

myTable1 <- "ID    GROUP 
     1     5     
     2     5         
     3     4.9        
     4     4.9   
     5     4.9   
     6     2.0"
Data <- read.table(text=myTable1, header = TRUE)

myTable2 <- "ID     GROUP
     1      4.9
     2      4.8
     3      4.6
     4      4.6
     5      4.6"
Data <- read.table(text=myTable2, header = TRUE)

数据来自不同的 .csv 文件。并且没有标题。我将它们的路径存储在一个名为 file_names 的列表中,并像这样读取文件:

data_list <- lapply(file_names, read.csv , header=FALSE, sep=",")

要添加我使用的标题:

data_list <- lapply(df, function(df) {colnames(df) <-c("ID", "Group"); df})

每个数据框可以在“组”列中包含不同的项目,例如 myTable2 不包含“组”中值为 2.0 或 5 的项目。列的长度可能不同。

我想要的是计算每个文件的“组”列中每个项目的出现次数。为了比较出现的次数,数据应按以下格式存储在单独的数据框中:

Group   Table 1  Table 2
  5        2        0
 4.9       3        1
 4.8       0        1   
 4.7       0        0
 4.6       0        1
 2.0       1        0

标签: rdataframecount

解决方案


library(tidyverse)

# function that reads file and stores name of file as a column
ReadFile = function(x) {read.csv(x) %>% mutate(id=x)}

# apply function to each file and combine as a dataframe
dt = list.files(pattern = "[.]csv$") %>% map_df(ReadFile)

dt %>%
  count(id, GROUP) %>%      # count file name and group
  spread(id, n, fill = 0)   # reshape

# # A tibble: 5 x 3
#   GROUP myTable1.csv myTable2.csv
#   <dbl>        <dbl>        <dbl>
# 1   2              1            0
# 2   4.6            0            3
# 3   4.8            0            1
# 4   4.9            3            1
# 5   5              2            0

推荐阅读