Re: [R] UNIX-like "cut" command in R

From: Petr Savicky <>
Date: Tue, 03 May 2011 10:03:29 +0200

On Tue, May 03, 2011 at 01:39:49AM -0500, Mike Miller wrote:
> On Tue, 3 May 2011, Christian Schulz wrote:
> >
> >x <- "this is a string"
> >unlist(strsplit(x," "))[c(1,4)]
> Thanks. I did figure that one out a couple of messages back, but to get
> it do behave like "cut -d' ' -f1,4", I had to add a paste command to
> reassemble the parts:
> paste(unlist(strsplit(x," "))[c(1,4)], collapse=" ")
> Then I wasn't sure if I could do this to every element of a vector of
> strings without looping -- I have to think not.

Try the following

  x <- c("this is a string", "this is a numeric")

  reassemble <- function(x, ind) paste(x[ind], collapse=" ")

  vapply(strsplit(x," "), reassemble, "character", c(1, 4))

  [1] "this string" "this numeric"

Hope this helps.

Petr Savicky. mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Thu 05 May 2011 - 06:25:10 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 05 May 2011 - 07:00:06 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive