Apologies, in general a fairly new programmer here, with R representing my only language so far.
So I'm trying to process some slightly noisy research data to give me the integral of the area contained within my signals. I've managed to source a highly relevant python script that does pretty much exactly what I want, but as I don't actually know python myself, and I've already got the data pipeline written in R, I was hoping to perform a similar task in R. Is the code below something that I could get running in R and move forward without having to learn an additional language?
To make the question more specific: how can I feed a list of highly specific parameters for what to integrate into R so I can tune the algorithm to only catch signals over a certain magnitude and duration? In this case, the signal magnitude included in the code is at least 0.5 (arbitrary units in this code), and I don't believe they have a minimum duration of signal.
import pandas as pd
import numpy as np
def integrate(data):
#This is the part where we analyze the data
y_vals = data["data"].values
x_vals = data["time"].values
#start by finding the location of all the signal
signal_locs = []
start_loc = -1
stop_loc = -1
for i in range(0,len(y_vals)-1):
if abs(y_vals[i+1]-y_vals[i]) > 0.5:
if start_loc == -1:
start_loc = i+1
else:
stop_loc = i
signal_locs.append((start_loc,stop_loc))
start_loc = -1
stop_loc = -1
#if the signal extends to the end of the dataset
if start_loc != -1 and stop_loc == -1:
stop_loc = len(y_vals)-1
signal_locs.append((start_loc,stop_loc))
#loop over all signal locs
integral = 0
tot = 0
for block in signal_locs:
#sometimes the signal might be the last part of your dataset *shrugs*
bkg_slope = 0
if block[1] == len(y_vals)-1:
bkg_slope = (y_vals[block[0]-1]-y_vals[block[0]-2])/(x_vals[block[0]-1]-x_vals[block[0]-2])
else:
bkg_slope = (y_vals[block[1]+1]-y_vals[block[0]-1])/(x_vals[block[1]+1]-x_vals[block[0]-1])
bkg_offset = y_vals[block[0]-1]
for i in range(block[0],block[1]):
bkg = (bkg_slope*(x_vals[i]-x_vals[block[0]-1]) + bkg_offset)
signal = y_vals[i] - bkg
integral += signal * (x_vals[i+1]-x_vals[i])
return integral