[R] UNIX-like "cut" command in R
Petr Savicky
savicky at praha1.ff.cuni.cz
Tue May 3 10:03:29 CEST 2011
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.
More information about the R-help
mailing list