On Fri, 2005-08-26 at 22:39 +0530, A Mani wrote:> Hello,
> Easy ways to "unpaste"?
> xp <- paste(x2, x3) # x2, x3 are two non-numeric columns.
> .............
> .........................
> xfg <- data.frame(xp,sc1, sc2, sc3) # sc1,sc2, sc3 are numeric cols.
>
> I want xp to be split up to form a new dataframe of the form (x3, sc1,
> sc2, sc3).
> IMPORTANT info : elements of xp have the form abc<space>efg, with abc
> in x2 and efg in x3.
>
> Thanks in advance,
I think I understand what you are trying to do. Hopefully the below may
be helpful:
# Create the data frame with 3 rows
x2 <- letters[1:3]
x3 <- LETTERS[1:3]
xp <- paste(x2, x3)
sc1 <- rnorm(3)
sc2 <- rnorm(3)
sc3 <- rnorm(3)
xfg <- data.frame(xp, sc1, sc2, sc3)
> xfg
xp sc1 sc2 sc3
1 a A 1.3479123 -1.0642578 0.2479218
2 b B -0.1586587 1.1237456 -1.3952176
3 c C 2.7807484 -0.9778066 -1.9322279
# Use strsplit() here to break apart 'xp' using " " as the
split
# Use "[" in sapply() to get the second (2) element from each
# 'xp' list pair. Note that I use as.character() here, since xfg$xp is
# a factor.
# See the output of: strsplit(as.character(xfg$xp), " ")
# for some insight into this approach
xp.split <- sapply(strsplit(as.character(xfg$xp), " "),
"[", 2)
# show post split values> xp.split
[1] "A" "B" "C"
# Now cbind it all together into a new data frame
# don't include column 1 from xfg (xp)
xfg.new <- cbind(xp.split, xfg[, -1])
> xfg.new
xp.split sc1 sc2 sc3
1 A 1.3479123 -1.0642578 0.2479218
2 B -0.1586587 1.1237456 -1.3952176
3 C 2.7807484 -0.9778066 -1.9322279
See ?strsplit for more information.
HTH,
Marc Schwartz