[R] Beginner: how to split up character string into different columns

arun smartpink111 at yahoo.com
Tue Mar 18 00:25:22 CET 2014


Hi,
May be this helps:
dat <- read.table(text="Sample
SFLS01A
SFHS05B",sep="",header=TRUE,stringsAsFactors=FALSE)
dat1 <- setNames(as.data.frame(do.call(rbind,strsplit(gsub("([[:alpha:]]+)(\\d+)([[:alpha:]]+)","\\1 \\2 \\3",dat$Sample)," ")),stringsAsFactors=FALSE),c("site","tree","rep"))

#or

 dat2 <- setNames(read.table(text=gsub("([[:alpha:]]+)(\\d+)([[:alpha:]]+)","\\1 \\2 \\3",dat$Sample),sep="",header=FALSE,colClasses=rep("character",3)),c("site","tree","rep"))
 identical(dat1,dat2)
#[1] TRUE




On Monday, March 17, 2014 5:48 PM, jmcable <jmcable at alaska.edu> wrote:
Hello,
I'm an R beginner and am not sure how to address this question. I've read
through tutorials and am still stuck.

I have a column in my data called "Sample". The samples are listed as four
sites (SFHS, SFLS, NFLS, NFHS) with tree numbers (01 through 23) and
replicates per tree (A and B). So, a typical sample name would look like:
SFLS01A or SFHS05B.  

I need to split this column into three columns (site, tree, and rep), but I
can't figure this out. Does someone have advice / suggestions?

Thanks so much! Jessie



--
View this message in context: http://r.789695.n4.nabble.com/Beginner-how-to-split-up-character-string-into-different-columns-tp4686998.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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