Ted Mosby - 1 year ago 122

R Question

Data:

`x <- seq(0, 1, len = 1024)`

pos <- c(0.1, 0.13, 0.15, 0.23, 0.25, 0.40, 0.44, 0.65, 0.76, 0.78, 0.81)

hgt <- c(4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2)

wdt <- c(0.005, 0.005, 0.006, 0.01, 0.01, 0.03, 0.01, 0.01, 0.005, 0.008, 0.005)

pSignal <- numeric(length(x))

for (i in seq(along=pos)) {

pSignal <- pSignal + hgt[i]/(1 + abs((x - pos[i])/wdt[i]))^4

}

df = as.data.frame(rbind(pSignal,pSignal,pSignal))

dflist=list(df,df,df)

I'm trying to run this pracma package's findpeaks() function to find the local maxima of each row in each data.frame in the list, dflist. The output is a N x 4 array. N = the number of peaks. So in the first row of the first data.frame if it finds 4 peaks, it will be a 4x4 matrix. My goal is to loop this function over every row in each data.frame and store the matrix that is output in a list.

My code:

`## Find Peaks`

pks=list()

for (i in 1:length(dflist)){

for (j in 1:length(dflist[[i]])){

row = dflist[[i]][j,]

temppks = findpeaks(as.vector(row,mode='numeric')

,minpeakheight = 1.1,nups=2)

pks[i][[j]]=rbind(pks,temppks)

}

}

This doesn't seem to be doing quite what I want it too. any ideas?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

A combination of apply() and sapply() could do the work:

```
my.f.row <- function(row) findpeaks(as.vector(row,mode='numeric'), minpeakheight = 1.1, nups=2)
sapply(dflist, function(df.i) apply(df.i, 1, my.f.row))
```

eventually you have to reorganize the result.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**