[R] ?nchar ?strsplit

arun smartpink111 at yahoo.com
Mon Aug 27 23:36:05 CEST 2012



HI,

#In addition to,
nchar1<-nchar(gsub("[^/]","",x$ID)) 
 max(nchar1) 
#[1] 3 
library(stringr) 
 data.frame(str_split_fixed(x$ID,"/",max(nchar1)+1))
#or strsplit(as.character(x$ID),"/")
 
#You can also use:
strsplit(gsub("(.*)/(.*)","\\1 \\2",gsub("(.*)/(.*)/(.*)","\\1 \\2 \\3",gsub("(.*)/(.*)/(.*)/(.*)","\\1 \\2 \\3 \\4",x$ID)))," ")
#[[1]]
#[1] "abc" "def"

#[[2]]
#[1] "abc" "def" "ghi"

#[[3]]
#[1] "abc"

#[[4]]
#[1] "mno" "pqr" "st"  "ab" 

A.K.


----- Original Message -----
From: Sapana Lohani <lohani.sapana at ymail.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Monday, August 27, 2012 2:40 PM
Subject: [R] ?nchar ?strsplit

Hi, my data frame is

x<-data.frame(ID=c("abc/def","abc/def/ghi","abc","mno/pqr/st/ab"))

I want to split my column ID using "/" as the place to split. How can I do that without telling the code how many sub-columns. I could use nchar(gsub("[^/]","",x$ID)) to get how many "/" are in each row of the column, but could not use it to split ID in.

Thanks

    [[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