1

I have two lists, list1 and list2 which has 77103 elements each with each row being a dataframe with 1 row and 100 columns. I am trying to do linear interpolation using approx function in R and I get the following error.

***`Error in Y[row, ] : incorrect number of dimensions`***

Here is an example code for what I am trying to do.


a1<- c(2.5, 7.8, 6.5, 9.2, 10.2)
a2<- c(1.1, 2.5, 3.9, 7.2, 11.2)
a3<- c(2.7, 5.8, 7.2, 12.2, 14.2)
a<- as.list(data.frame(a1,a2,a3))
b1<-c(0.1,2,3.3, 4.5, 6.7)
b2<-c(1.1,2.9,3.4,5.5,7.7)
b3<-c(0.7,2.1,3.8,4.4,5.5)
b<- as.list(data.frame(b1,b2,b3))
df<- mapply(function(X,Y) {
  sapply(1:3, function(row) approx(X[row,], Y[row,], xout=seq(0,4, by=1), method="linear"))
}, X=a, Y=b)

What could be the reason for this to happen? Please suggest alternate ideas to bypass this error. Thanks

Maja
  • 23
  • 4
  • 2
    Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Jan 24 '20 at 18:05
  • @Tung. Thank you! I have added a reproducible example. – Maja Jan 24 '20 at 20:39
  • you should use `X[[row]], Y[[row]]` to access list values – YOLO Jan 24 '20 at 20:43
  • why are you doing `sapply(1:3` ? – YOLO Jan 24 '20 at 20:44
  • @YOLO Thank you for your suggestion. Now I have new error Error in approx(X[[row]], Y[[row]], xout = seq(0, 4, by = 1), method = "linear", : need at least two non-NA values to interpolate – Maja Jan 24 '20 at 20:58
  • yes, I fixed it. about to post my answer. can you tell the expected output ? how should it look ? – YOLO Jan 24 '20 at 21:10
  • Awesome. I am expecting only the corresponding interpolated values. For the above example I expect a dataframe with 3 rows and 5 columns. Thanks – Maja Jan 24 '20 at 21:13
  • @YOLO, Appreciate your time – Maja Jan 24 '20 at 22:10

1 Answers1

1

Here's a way you can do:

f <- Map(function(X,Y) {
  approx(X, Y, xout=seq(0,4, by=1), method="linear")$y # could use $x also
},a, b)

# convert to data frame
f <- data.table::transpose(as.data.frame(f))

 V1 V2       V3        V4       V5
1 NA NA       NA 0.5000000 1.300000
2 NA NA 2.257143 3.0785714 3.463636
3 NA NA       NA 0.8354839 1.287097
YOLO
  • 20,181
  • 5
  • 20
  • 40