How to use function spectrum in R to perform spectral analysis

I intend to perform spectral analysis with R stat:spectrum and then plot power spectrum.

My code is listed here:

  t <- seq(0,1024,by=0.1)
x <- cos(2*pi*t) + 0.75*sin(2*pi*4*t) + 2*sin(2*pi*6*t)
x.spec <- spectrum(x,log="no",span=5,plot=FALSE)
del <- 0.1
spx <- x.spec$freq/del spy <- 2*x.spec$spec
plot(spy~spx,xlab="frequency",ylab="spectral density",type="l")


the signal has 3 periodic components with 1 Hz, 4 Hz, 6 Hz, but the final spectrum only shows the first 2 frequencies, without 6 Hz. And I don't know why the range of x.spec$freq is [0,0.5] before scaling. Please tell me my possible concept misunderstanding and guide me how to plot the spectrum correctly. Thank you very much. 2 Answers Hi: Your sampling frequency is$f_{s} = 10 $but the frequency of the third component is$f_{3} = 6$.. Therefore, the nyquist criterion for the maximum frequency is not being met because$2 * 6 = 12$which is not less than$f_{s} = 10$. I'm new at this but hopefully this is the reason why. Someone will surely correct me if not. • your answer helps me much, when I change sampling frequency to 20 Hz, that sampling period ts = 0.05 s, the result comes to what I expected. – dawei Feb 19 '18 at 3:24 • i'm glad it helped. in fact, this is the first "pure-dsp" question that I've answered on this list so thanks for the question. – mark leeds Feb 19 '18 at 6:02 as @mark leeds suggested, my code changed as followed: ts <- 0.05 fs <- 1/ts t <- seq(0,512,by=ts) x <- cos(2*pi*t) + 0.75*sin(2*pi*4*t) + 2*sin(2*pi*6*t) x.spec <- spectrum(x,log="no",span=5,plot=FALSE) spx <- x.spec$freq * fs
spy <- 2*x.spec\$spec
plot(spy~spx,xlab="frequency",ylab="spectral density",type="l")