[R] How I can rearrange columns in data.frame?
Berend Hasselman
bhh at xs4all.nl
Mon May 27 20:35:02 CEST 2013
On 27-05-2013, at 20:17, Kristi Glover <kristi.glover at hotmail.com> wrote:
> Hi R-User,
> I am wondering how I can rearrange columns in a table in R. I do have very big data set (4500 columns). I have given an example of the data set.
>
>> dput(dat)
> structure(list(preV1001A1b = c(0.59, 0.3, 0.78, 0.43), preV15A1b = c(0.57,
> 0.62, 0.51, 0.95), preV2032A1b = c(0.4, 0.8, 0.24, 0.34), preV2035A1b = c(0.95,
> 0.67, 0.81, 0.8), preV59A1b = c(0.05, 0.57, 0.03, 0.5)), .Names = c("preV1001A1b",
> "preV15A1b", "preV2032A1b", "preV2035A1b", "preV59A1b"), class = "data.frame", row.names = c(NA,
> -4L))
>
> I wanted to make like this
>> dput(dat1)
> structure(list(preV15A1b = c(0.57, 0.62, 0.51, 0.95), preV59A1b = c(0.05,
> 0.57, 0.03, 0.5), preV1001A1b = c(0.59, 0.3, 0.78, 0.43), preV2032A1b = c(0.4,
> 0.8, 0.24, 0.34), preV2035A1b = c(0.95, 0.67, 0.81, 0.8)), .Names = c("preV15A1b",
> "preV59A1b", "preV1001A1b", "preV2032A1b", "preV2035A1b"), class = "data.frame", row.names = c(NA,
> -4L))
> Any suggestions.
> KG
dat2 <- dat[,c("preV15A1b", "preV59A1b", "preV1001A1b", "preV2032A1b", "preV2035A1b")]
identical(dat1,dat2)
or something like this:
dat3.cols <- match(c("preV15A1b", "preV59A1b", "preV1001A1b", "preV2032A1b", "preV2035A1b"), names(dat))
dat3 <- dat[,dat3.cols]
identical(dat3,dat2)
A general solution will depend on the new ordering of your columns.
Berend
More information about the R-help
mailing list