R: Spline Across/Horizontally/Across a Matrix -
i have matrix similar this:
1 2 3 4 5 1.4 na 2.3 0.2 na b na 3.2 1.2 na na c 3.5 na na na na d 2.1 1.9 na na na
i need interpolate na's in matrix. able when specify row in:
fmm = spline(x = 1:5, y = rationa[1,1:5], xout = 1:5, method = "fmm")
but not entire table @ once.
plus, instead of doing each row, each column. is, instead of interpolating in terms of (1.4, na, 2.3, 0.2, na), uses (1.4, na, 3.5, 2.1). need former.
how spline per row instead of columns without specifying row?
thank you.
you can utilize function apply execute specified function each row or column of matrix
sample data
*txt=" 1 2 3 4 5 1.4 na 2.3 0.2 na b na 3.2 1.2 na na c 3.5 na na na na d 2.1 1.9 na na na" df=read.table(text=txt,header=t)*
sample calculation
fmm = spline(x = 1:5, y = df[1,1:5], xout = 1:5, method = "fmm")
function calculate each row
myfun<-function(yrow){ fmm = spline(x = 1:5, y = yrow, xout = 1:5, method = "fmm") return(fmm$y) }
evaluate each row of matrix. note, transpose needed since output of "apply" column vector.
df_interp <- t(apply(df, 1, myfun))
resulting output
df_interp [,1] [,2] [,3] [,4] [,5] 1.4 2.7 2.3 0.2 -3.6 b 5.2 3.2 1.2 -0.8 -2.8 c 3.5 3.5 3.5 3.5 3.5 d 2.1 1.9 1.7 1.5 1.3
r matrix interpolation spline
No comments:
Post a Comment