I came across the following statement:
For every space $X$ we have the exact sequences of homotopy classes $[X, \mathbb{Z}_2] \to [X, \mathbb{S}^n] \to [X, \mathbb{RP}^n] \to [X, \mathbb{RP}^\infty]$
Here the maps are the obvious ones: the first induced by the inclusion, the second by the projection and the third by the inclusion. The exactness of the sequence is to be intended as between spaces with identity (null-homotopic map).
I cannot understand the exactness at last step. I know there are the two exact sequences
$[X, \mathbb{Z}_2] \to [X, \mathbb{S}^n] \to [X, \mathbb{RP}^n]$
$[X, \mathbb{Z}_2] \to [X, \mathbb{S}^\infty] \to [X, \mathbb{RP}^\infty]$
but I don't how I can glue them together.
I believe you're asking about exactness at $[X, \mathbb{RP}^n]$. That is, you'd like to know why we have
$$\operatorname{ker}([X, \mathbb{RP}^n] \xrightarrow{i\ \circ} [X, \mathbb{RP}^{\infty}]) = \operatorname{im}([X, S^n] \xrightarrow{\pi\ \circ } [X, \mathbb{RP}^n])$$
where $i : \mathbb{RP}^n \to \mathbb{RP}^{\infty}$ is the inclusion and $\pi : S^n \to \mathbb{RP}^n$ is the projection.
Suppose $n > 1$.
If $f \in \operatorname{ker}([X, \mathbb{RP}^n] \xrightarrow{i\ \circ} [X, \mathbb{RP}^{\infty}])$, then $i\circ f$ is nullhomotopic so $(i \circ f)_* : \pi_1(X) \to \pi_1(\mathbb{RP}^{\infty})$ is the zero map. But $(i\circ f)_* = i_*\circ f_*$ and $i_*$ is an isomorphism, so we see that $f_*$ is the zero map. Therefore, there is a lift $\tilde{f}$ of $f$ to the universal cover of $\mathbb{RP}^n$. That is, there is a map $\tilde{f} : X \to S^n$ such that $f = \pi\circ\tilde{f}$ and hence $f \in \operatorname{im}([X, S^n] \xrightarrow{\pi\ \circ } [X, \mathbb{RP}^n])$.
Conversely, if $f \in \operatorname{im}([X, S^n] \xrightarrow{\pi\ \circ } [X, \mathbb{RP}^n])$, then $f$ is homotopic to a map $\pi\circ g$, so $i\circ f$ is homotopic to $i\circ\pi\circ f$. Now we have $(i\circ f)_* = (i\circ \pi\circ f)_* = i_*\circ \pi_*\circ f_*$. Note that $\pi_*$ is the zero map as $S^n$ is simply connected, so $i\circ f$ lifts to the universal cover of $\mathbb{RP}^{\infty}$. As the universal cover of $\mathbb{RP}^{\infty}$ is contractible, we see that $i\circ f$ is nullhomotopic and hence $f \in \operatorname{ker}([X, \mathbb{RP}^n] \xrightarrow{i\ \circ} [X, \mathbb{RP}^{\infty}])$.
The argument for $n = 1$ is completely analogous. One just needs to realise that the image of $\pi_* : \pi_1(S^1) \to \pi_1(\mathbb{RP}^1)$ is precisely the kernel of $i_* : \pi_1(\mathbb{RP}^1) \to \pi_1(\mathbb{RP}^{\infty})$.