首页 > 解决方案 > 替换 for 循环 - R 脚本

问题描述

有没有办法For loop用family函数替换下面代码中的,Apply或者以任何其他方式表示它以加快代码执行:

line = strsplit(textFileContent, " ")
for(i in 2:n){ #looping from 2nd line to nth line of an input txt file

  a = as.numeric(line[[i]][1]) #starting index in a matrix
  b = as.numeric(line[[i]][2]) #ending index in a matrix
  k = as.numeric(line[[i]][3]) #a number

  mat[1,a:b] = mat[1,a:b] + k
  #mat is a matrix of 5 zeros.
  #mat = [0, 0, 0, 0, 0]. 
  #Each time a value (k) will be added to all the elements between starting and ending index
}

编辑

示例输入(文本文件内容):

5 3

1 2 100

2 5 100

3 4 100

在这里,输入的第一行包含 2 个空格分隔的数字。第一个数字表示mat矩阵最初将包含 5 个零。第二个数字表示第一行后面有多少行。在上面的代码中,它被视为n.

下一行包含 3 个空格分隔的数字。第一个是a,第二个是b,第三个是k

注意:a、b、k、n 和第一行的第一个数字的值可能会有所不同。

输出:

[100、200、200、200、100]

修改后的代码

filepath = "C:\\textFileContent.text"
con = file(filepath, "r")
inp1 = readLines(con, n = -1, warn = FALSE)

line = strsplit(inp1, " ")

matadd<- function(line) {
  a<-as.numeric(line[1])
  b<-as.numeric(line[2])
  k<-as.numeric(line[3])
  mat[1,a:b]<<-mat[1,a:b]+k
}
mat<-matrix(0,nrow=1,ncol=as.numeric(line[[1]][1]))
temp<-sapply(line[2:(as.numeric(line[[1]][2])+1)],matadd)
cat(apply(mat, 1, max))
close(con)

使用上面提供的示例输入,line如下所示:

> line
[[1]]
[1] "5" "3"

[[2]]
[1] "1"   "2"   "100"

[[3]]
[1] "2"   "5"   "100"

[[4]]
[1] "3"   "4"   "100"

提前致谢。

标签: rfor-loop

解决方案


好的,这是一个猜测,但如果我正确地得到了你的请求和你的数据结构,这应该可以工作:

matadd<- function(line) {
  a<-as.numeric(line[1])
  b<-as.numeric(line[2])
  k<-as.numeric(line[3])
  mat[1,a:b]<<-mat[1,a:b]+k
}
# Create the matrix with all zeros
mat<-matrix(0,nrow=1,ncol=as.numeric(line[[1]][1]))
# sapply the function on rows 2 thru end of the list
sapply(line[2:(as.numeric(line[[1]][2])+1)],matadd)

实际上我本可以使用length列表中的,想想看...

例如,使用line<-list(c(5,2),c(2,3,5),c(1,4,2)),结果如下:

      [,1] [,2] [,3] [,4] [,5] 

 [1,]   2    7    7    2    0

推荐阅读