R 为了在多个csv文件中找到特定行的平均值,我应该做什么?
我试图根据多个CSV文件中的行找到平均值。我已从目录中提取了该文件,并对其进行了修改,使其仅包含2个适用的列。问题是,我想根据目录中所有66个CSV文件的值来查找特定行的平均值。我的代码基本上卡在这里:R 为了在多个csv文件中找到特定行的平均值,我应该做什么?,r,R,我试图根据多个CSV文件中的行找到平均值。我已从目录中提取了该文件,并对其进行了修改,使其仅包含2个适用的列。问题是,我想根据目录中所有66个CSV文件的值来查找特定行的平均值。我的代码基本上卡在这里: # Set path to folder folder.path <- getwd() # Get list of csv files in folder filenames <- list.files("Path", pattern = "*.csv
# Set path to folder
folder.path <- getwd()
# Get list of csv files in folder
filenames <- list.files("Path", pattern = "*.csv", full.names = TRUE)
# Read all CSV files in the folder and create a list of data frames
ldf <- lapply(filenames, read.csv)
# Select hr and stimulus columns in each dataframe in the list
ldf <- lapply(ldf, "[", c("Variable1", "Variable2"))
#See the variable left in each CSV files
lapply(ldf, names)
#设置文件夹的路径
folder.path您可以使用lappy
对ldf
中的每个数据帧进行迭代,并对它们进行aggregate
以获得Variable1
中每个唯一值的Variable2
平均值
result <- lapply(ldf, function(x) aggregate(Variable1~Variable2, x, mean, na.rm = TRUE))
我们可以使用data.table
方法
library(data.table)
out <- lapply(ldf, function(x) setDT(x)[,
.(Variable1 = mean(Variable1, na.rm = TRUE)),
by = Variable])
库(data.table)
出来
library(data.table)
out <- lapply(ldf, function(x) setDT(x)[,
.(Variable1 = mean(Variable1, na.rm = TRUE)),
by = Variable])