apply strsplit rowwise

Misha picture Misha · Sep 13, 2010 · Viewed 17.8k times · Source

Im trying to split a string on "." and create additional columns with the two strings before and after ".".

tes<-c("1.abc","2.di","3.lik")
dat<-c(5,3,2)
h<-data.frame(tes,dat)
h$num<-substr(h$tes,1,1)

h$prim<-unlist(strsplit(as.character(h$tes),"\\."))[2]
h$prim<-sapply(h$tes,unlist(strsplit(as.character(h$tes),"\\."))[2])

I´d like h$prim to contain "abc","di","lik"..However I´m not able to figure it out. I guess strsplit is not vectorized, but then I thought the sapply version should have worked. However I assume it should be easy:-)

Regards, //M

Answer

rcs picture rcs · Sep 13, 2010

This should do the trick

R> sapply(strsplit(as.character(h$tes), "\\."), "[[", 2)
[1] "abc" "di"  "lik"