Rescale column in dataframe?

2.3k views Asked by At

I have a dataframe called data where I would like to rescale the values in the 4th field to a range of 0-1000 and round the scaled value to the nearest integer. I'm trying to use ddply, round and rescale:

scaled_data <- ddply(data, round(rescale(data[,4], to=c(0,1000), from=range(data[,4], na.rm=TRUE)), 0)

The above code throws this error:

Error in `[.data.frame`(envir, exprs) : undefined columns selected

Can anyone point out the problem or a better way to accomplish what I am trying to do?

1

There are 1 answers

0
Ben Bolker On BEST ANSWER

I think you're making it too complicated -- I don't see why you need ddply at all.

dd[,4] <- round(ggplot2::rescale(dd[,4],to=c(0,1000))

(I'm using ggplot2::rescale because you did, but (x-min(x))/diff(range(x))*1000 would do the same thing)

Or if you know the name of the fourth column you can:

dd <- transform(dd,fourth=rescale(fourth,to=c(0,1000)))