r - 替换 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"
提前致谢。
解决方案
好的,这是一个猜测,但如果我正确地得到了你的请求和你的数据结构,这应该可以工作:
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
推荐阅读
- algorithm - 检查 N^2 个元素是否可以转换为 N*N 对称矩阵的程序?
- c# - 如何在 C#(MonoDroid) 中将 EditText 长度限制为 6 个整数和 3 个小数位?
- angular - 我有一个“过滤器”功能,它假设根据名称过滤来自 Firestore 的数据。我能够从 firestore 获取全部数据
- javascript - 如何在文本区域内添加表情符号或图像图标?
- javascript - Ckeditor 工具栏项目在 Vue (Laravel) 中不可用
- python - 有什么方法可以绘制印度地图吗?
- javascript - ios os 中没有显示视频
- regex - 正则表达式灾难性回溯
- java - 为什么向上转换到父抽象类不起作用
- android - Ubuntu 或 Windows 上的 Packet Sender 等应用程序不接收从 Android Server Socket 发送的消息