[英]Apply function to NA matrix in R
I want to use the apply to use a function that I used to pull data via regular expressions and fill a matrix with it. 我想使用apply来使用我用来通过正则表达式提取数据并用它填充矩阵的函数。
planetdata = function(dline) {
new_line = unlist(strsplit(as.character(dline),"</td><td>"))
new_first_value = substring(new_line[1],9)
new_last_value =substring(new_line[11],1,nchar(new_line[11])-10)
new_line[1] <- new_first_value
new_line[11] <- new_last_value
new_data <- new_line
return(new_data)
}
new.dt = dt[21:1912]
exo.mat = matrix(data = NA, nrow=1892, ncol = 11)
colnames(exo.mat) <- c(exo.col.names)
apply(exo.mat,2,function(new.dt) planetdata(new.dt))
However, my matrix does not change and all the values are still NA. 但是,我的矩阵不变,并且所有值仍为NA。 Why is this happening?
为什么会这样呢?
Did you mean this? 你是这个意思吗
exo.mat[] <- apply(new.dt, 2, planetdata)
R usually passes by value, not by reference. R通常按值传递,而不是按引用传递。 Modifying a variable inside a function will generally not modify it outside.
在函数内部修改变量通常不会在函数外部进行修改。 You need to save the value out explicitly.
您需要明确保存该值。
Also, you were passing in the empty matrix to apply()
, it just didn't look that way because you made an anonymous function with a new.dt
parameter, which is different from the new.dt
variable you had in your session. 另外,您正在将空矩阵传递给
apply()
,看起来好像不是那样,因为您使用new.dt
参数创建了一个匿名函数,该参数不同于会话中使用的new.dt
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.