Not a good idea if you are on a single ticket for the two flights. International airports in the US do not have airside transit busses for international flights but major European airports such as London Heathrow do.
As you can see from the instructions on the LHR website, the recommended route from terminal T2 to terminal T5 is different, depending on whether you hold a single ticket ("connecting passenger") or two tickets from separate airlines ("self-connecting passenger").
If you take a taxi or Heathrow Express or whatever to get from one LHR terminal to the other, it will cost you time as you will have to go through customs/passport control twice (first out to get to the taxi stand or train stop and then in again at the departure terminal) and through security once. If you can stay airside and can take the transit busses, you only have to go through security once before the flight to Madrid and no passport/immigration control at LHR, only at Madrid.
Buying a single ticket (if you can) has a big advantage and allows for shorter connection times between two international flights, such as US-LHR-Madrid.