[R] Splitting the Elements of character vector

arun smartpink111 at yahoo.com
Tue Apr 16 15:00:48 CEST 2013


Hi,
Try:
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),stringsAsFactors=FALSE)
 df$currency<-unlist(lapply(str_split(df[,1],"_"),`[`,1))
 df$tenor<-unlist(lapply(str_split(df[,1],"_"),function(x) {paste(x[-1],collapse="_")}))
 df[,c(3,4,2)]
 # currency tenor 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
A.K.



----- Original Message -----
From: Katherine Gobin <katherine_gobin at yahoo.com>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, April 16, 2013 8:38 AM
Subject: [R] Splitting the Elements of character vector

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.

I tried

strsplit(df$currency_type, "_")
Error in strsplit(df$currency_type, "_") : non-character argument

Kindly guide

Katherine

    [[alternative HTML version deleted]]


______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list