r/ how to apply lowess smoothing to variables that are initially unordered in data frame

StackOverflow https://stackoverflow.com/questions/20746383

  •  20-09-2022
  •  | 
  •  

Question

For Iris-data:

i <- iris[,1:4] # numerical variables in Iris-data
ord_i <- order(i[,1]) # order data frame by variable 1 ascending order 
low_i <- lowess(i[ord_i,1], f=1/10)[2] # compute lowess for ordered variable 1
i[ord_i,1] <- low_i # insert new values to original data

is successful. I tried and failed to generalize this into a function:

func1 <- function(x){
  func1_aux <- function(x,y){
  ord_x <- order(x[,y])
  low_y <- lowess(x[ord_x, y], f=1/10)[2]}    
apply(x, 2, func1_aux)}

func1(i)
Error in x[, y] : incorrect number of dimensions

I suspect the problem is in how variable name y and data frame x come from apply to func1_aux.

Any advice how to fix this or smarter way to do the task? Thanks!

Was it helpful?

Solution

It's not clear to me why you would want to do this, but here's one way to independently sort each column of a data frame and fit a lowess smooth to it:

i <- iris[, 1:4]
k <- apply(i, 2, function(x) lowess(x[order(x)], f=1/10)[[2]][match(x, x[order(x)])])

Using the double brackets, [[2]], ensures that the result, k, is a matrix rather than a list. Although this approach fits a lowess smooth to each column sorted independently, in order to keep the results in the same order as the original data frame i, you need to "unsort" it. That's what the [match(...)] part of the code is doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top