至于第一部分,这很简单。您可以在 lapply 循环中计算相关性并将它们写入新文件:
lapply(files, function(f) {
# Read CSV data
csv_data <- read.csv(f, header=TRUE)
# Calculate correlation
csv_data[, 4] <- cor(csv_data[, 2], csv_data[, 3])
# Create a new filename by replacing the ending of the
# input file (.csv) with (_cor.csv)
newfile <- gsub("\\.csv$", "_cor.csv", f)
write.csv(csv_data, file = newfile, quote = FALSE)
})
由于 R 希望 data.frames 中的列具有相同的行数,这将用相关值填充第 4 列的每一行。我会顺其自然,但如果你有很多数据,这可能会浪费存储空间。这是一个不太优雅的解决方案,仅在第一行中具有相关性:
lapply(files, function(f) {
# Read CSV data
csv_data <- read.csv(f, header=TRUE)
# Calculate correlation
csv_data[, 4] <- cor(csv_data[, 2], csv_data[, 3])
# Now delete duplicate values of cor
csv_data[2:nrow(csv_data), 4] <- NA
# Create a new filename by replacing the ending of the
# input file (.csv) with (_cor.csv)
newfile <- gsub("\\.csv$", "_cor.csv", f)
# Now when we write, we tell R to write an empty string when it encounters
# missing values
write.csv(csv_data, file = newfile, quote = FALSE, na = "")
})
还有:
当您使用已经存在的函数(如lapply() 或cor())时,您不需要调用function()。仅当您想自己定义新函数时才需要使用它。
如果您想在单个 data.frame 中输出,请尝试:
my_df <- do.call(rbind,
lapply(files, function(f) {
# Read CSV data
csv_data <- read.csv(f, header=TRUE)
# Calculate correlation
data.frame(File=f, Correlation=cor(csv_data[, 2], csv_data[, 3]))
})
)