[R] Splitting the Elements of character vector

Gabor Grothendieck ggrothendieck at gmail.com
Tue Apr 16 15:00:20 CEST 2013


On Tue, Apr 16, 2013 at 8:38 AM, Katherine Gobin
<katherine_gobin at yahoo.com> wrote:
> Dear R forum
>
> I have a data.frame
>
> df = data.frame(currency_type = c("EURO_o_n", "EURO_o_n", "EURO_1w", "EURO_1w", "USD_o_n", "USD_o_n", "USD_1w", "USD_1w"), rates = c(0.47, 0.475, 0.461, 0.464, 1.21, 1.19, 1.41, 1.43))
>
>   currency_type     rates
> 1      EURO_o_n   0.470
> 2      EURO_o_n   0.475
> 3       EURO_1w   0.461
> 4       EURO_1w   0.464
> 5       USD_o_n    1.210
> 6       USD_o_n    1.190
> 7        USD_1w    1.410
> 8        USD_1w    1.430
>
>
> I need to split the values appearing under currency_type to obtain following data.frame in the "original order"
>
> currency     tenor   rates
> EURO         o_n     0.470
> EURO         o_n     0.475
> EURO         1w      0.461
> EURO         1w      0.464
> USD           o_n     1.210
> USD           o_n     1.190
> USD           1w      1.410
> USD           1w      1.430
>
> Basically I need to split the currency name and tenors.
>

Try sub:

with(df, data.frame(
   currency = sub("_.*", "", currency_type),
   tenor = sub("^[^_]*_", "", currency_type),
   rates)
)

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list