-2

我有以下数据:

NCNC    413
JJNC    183

我想添加另一列数据,以百分比形式给出:the percent NCNC and JJNC values.

理想情况下,我想知道如何将此脚本应用于文件夹中的多个文件。谢谢。

4

1 回答 1

1

我这里不得不做很多假设,因为你对你的具体情况还不是很清楚。如果您已将工作目录设置为文件所在的位置,并且它们是 csv 文件,则以下内容可能对您有用。有许多因素可能会阻止它工作,所以如果没有,您可能需要返回更多细节。

#Get list of all files in the folder
files <- list.files("./", ".csv")
#Make a function to read in a file, produce the percent column
perc.fun <- function(x) {
  dat <- read.csv(x, head = FALSE)
  dat$perc <- dat[,2]/sum(dat[,2])
  write.table(dat, paste("perc", x, sep = "_"), sep = ",", row.names = FALSE, col.names = FALSE)
}
#Use lapply to go through the list of files and apply the function
lapply(files, perc.fun)

输出文件应与perc_旧文件名位于同一文件夹中。如果您的文件中有标题,那么您需要进行修改以解决此问题。

于 2013-07-04T07:14:17.887 回答