fourier transform in r

To perform Fourier transform in R, we can use the built-in function fft().

The following is an example that shows how to compute the Fourier transform of a sine wave:

main.r
# Generate a sine wave with a frequency of 10 Hz
fs <- 100      # Sampling frequency
t <- seq(0, 1, 1/fs)    # Time vector
f <- 10                  # Frequency of the sine wave
x <- sin(2*pi*f*t)     # Sine wave signal

# Compute the Fourier transform
X <- fft(x)

# Create a vector of frequencies
freq <- seq(0, fs/2, length.out = length(X)/2 + 1)

# Plot the magnitude of the Fourier transform
plot(freq, abs(X[1:length(freq)]) / length(X), 
     main = "Magnitude spectrum of a sine wave",
     xlab = "Frequency (Hz)", ylab = "Magnitude")
543 chars
17 lines

In this example, we first generated a sine wave signal with a frequency of 10 Hz by using the sin() function. We then called the fft() function to compute its Fourier transform.

The Fourier transform produces a complex-valued output, which represents the frequency-domain representation of the signal. To plot the magnitude of the Fourier transform, we can use the abs() function to compute its absolute value. We also divided by the length of the signal to normalize the magnitude spectrum.

Finally, we plotted the magnitude spectrum using the plot() function, and specified the x-label and y-label using the xlab and ylab arguments.

gistlibby LogSnag