I have to create a data frame with a column filled with runif numbers, but each number in a row is 10 times smaller than the previous one (this should be done 5 times). So, if the first number in a first row is 5, second is 0.5, 0.05, 0.005 and 0.0005 at the end. For example, in the code below, data frame has been made and I should replace first five values in OD column like explained above.

levels <- c("ref", "treat", "control")
x <- as.factor(labels)
a <- levels[x]
values <- runif(25,min=0,max=25)
my.data <- data.frame(labels = a, OD=values)

1 Answers

Alexis On

I'll give you a detailed answer. You'd like to make each number 10 times smaller than the previous, Which can be done with something like:

runif(1, min=0, max=25) / 10 ^ (0:4)

We include 0 in the exponents to keep the original number.

Then you want to apply that operation to each value in values, so you can use sapply for that.

sapply(values, "/", 10 ^ (0:4))

However, when each result is a vector, sapply binds them all column-wise, so we transpose the result with t. Since you want a data frame, you could simply end up with:

data.frame(labels=a, t(sapply(values, "/", 10 ^ (0:4))))

And maybe adjust column names afterwards with colnames.

BTW, your example is not reproducible, labels is not defined.