r - 计算数据帧列表中的出现次数并将结果存储在 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
解决方案
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
推荐阅读
- postgresql - docker-compose.yml,postgress,如何在 init.sql 文件中设置 db、tables 和 prepop?
- python - 单击按钮时运行python脚本
- python - Zapier 操作代码:Python 不会使用 input_data 变量运行
- javascript - 胜利堆栈中水平条的间距和大小?
- javascript - 使用 Jest 和 Enzyme,如何测试通过 props 传入的函数?
- javascript - 将 Python 字符串列表导入 Javascript 脚本(HTML 文件)
- python - 有没有更好的方法来覆盖 Marshmallow.fields.List?
- redirect - 登录站点 intead Admin/cmsadministration.aspx 后如何重定向到 kentico 的主页?
- javascript - JavaScript:以功能方式重新组织画布渲染
- java - 映射和数组列表,如果索引为 getEntry() 为 null,则添加“0”