R - 在For循环

时间:2017-08-02 18:28:35

标签: r csv for-loop assign substr

我在assing中使用for loop批量读取工作目录中的所有.csv个文件。然后我使用substr来清除文件的名称。我想为每个文件名添加一个列,以便以后在代码中进行更好的分析。但是,在清除文件名以添加列后,我在for loop中引用该文件时遇到问题。

#read in all files in folder
files <- list.files(pattern = "*.csv")
for (i in 1:length(files)){
  assign(substr(files[i], start = 11, stop = nchar(files[i])-4),  #clean file names
         read.csv(files[i], stringsAsFactors = FALSE))
  substr(files[i], start = 11, stop = nchar(files[i])-4)['FileFrom'] <- files[i]
}

2 个答案:

答案 0 :(得分:1)

near.match <- function(x, y, tol = .Machine$double.eps^0.5){ sapply(x, function(i){ res <- which(abs(y - i) < tol, arr.ind = TRUE)[1] if(length(res)) res else NA_integer_ }) } near.match(seq(0, 0.2, 0.05), seq(0, 0.2, 0.01)) # [1] 1 6 11 16 21 near.match(c(seq(0, 0.2, 0.05), 0.3), seq(0, 0.2, 0.01)) # [1] 1 6 11 16 21 NA 似乎不是正确的功能,我认为你需要在你设置的字符串cmd上使用<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function myFunction() { var val1 = $("#value1").val(); var val2 = $("#value2").val(); var sum = parseInt(val1) + parseInt (val2); if(sum > 100) { alert('Sum '+sum+ ' is greater than 100') } else { alert('Sum '+sum+ ' is less than 100') } } </script> </head> <body> <input type="text" class="input" id="value1"> <input type="text" class="input" id="value2"> <button type="button" onclick="myFunction()">Check</button> </body> </html>。内联注释解释更多:

assign

答案 1 :(得分:0)

这会有用吗?

#read in all files in folder
files <- list.files(pattern = "*.csv")
filesCopy <- files
for (i in 1:length(files)){
  assign(substr(files[i], start = 11, stop = nchar(files[i])-4),  #clean file names
         read.csv(files[i], stringsAsFactors = FALSE))
  substr(files[i], start = 11, stop = nchar(files[i])-4)['FileFrom'] <- filesCopy[i]
}