Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply strsplit rowwise

Tags:

r

strsplit

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

like image 229
Misha Avatar asked Sep 13 '10 19:09

Misha


4 Answers

This should do the trick

R> sapply(strsplit(as.character(h$tes), "\\."), "[[", 2)
[1] "abc" "di"  "lik"
like image 109
rcs Avatar answered Oct 20 '22 12:10

rcs


With the stringr package it's even easier:

library(stringr)
str_split_fixed(h$tes, fixed("."), 2)[, 2]
like image 30
hadley Avatar answered Oct 20 '22 10:10

hadley


This is the same as rcs' answer, but may be easier to understand:

> sapply(strsplit(as.character(h$tes), "\\."), function(x) x[[2]])
[1] "abc" "di"  "lik"
like image 8
Joshua Ulrich Avatar answered Oct 20 '22 10:10

Joshua Ulrich


This question appears several time on StackOverflow.

In exact form as yours:

  • Selecting first element of strsplit
  • Selecting second element separate by space
  • Selecting second element separate by dot I recommend this question to see in how many ways it could be achieved.

Some similar question in this topic:

  • Split without separator
  • First part as in your question but was change to more complex case

And if you care about speed then you should consider tip from John answer about fixed parameter to strsplit.

like image 7
Marek Avatar answered Oct 20 '22 11:10

Marek