Zach M.
Zach M.

Reputation: 1194

Restructuring Vectors in R

if i have a file containing say (age,weight,city,town,height) is there a way to restructure the file so that all the numeric data eithier comes first or second such as (age,weight,height,city,town) in a simple way. I want to know this because i have numeric and non numeric data about 10 columns long andhave to normalize using min/max only the numeric fields and it would be faster if they were all in one half of my dataset so i can just use a loop. Sorry i'm new to R and i'm using it in mac os if thats important.

Upvotes: 2

Views: 84

Answers (2)

joran
joran

Reputation: 173547

Why bother reordering the columns, when you can simply loop over them and scale the numeric ones as needed?

dat <- data.frame(x1 = runif(10),
                  x2 = letters[1:10],
                  x3 = rnorm(10),
                  x4 = LETTERS[1:10])

data.frame(lapply(dat,function(x){if (is.numeric(x)) scale(x) else x}))

An equivalent, although somewhat bizarre looking, solution using some handy plyr functions:

require(plyr)
colwise(function(x){if (is.numeric(x)) scale(x) else x})(dat)

the versions numcolwise and catcolwise may also be of some interest (although they return only the columns they act on).

Upvotes: 0

Sophia
Sophia

Reputation: 1951

Constructing a sample data.frame:

dat <- data.frame(age=runif(10), weight=runif(10), city="New York", town="any", height=runif(10))

That's how you can order the columns:

dat.ordered <- dat[,order(sapply(dat,is.numeric), decreasing=T)]

Upvotes: 2

Related Questions