I have a data.frame
in R
that consists in a number of columns with numerical values.
Like this:
A B C
0.6057 0.1644 6.93
0.5723 0.117 6.59
0.5614 0.1552 7.02
0.4102 0.1059 5.24
0.4945 0.0857 6.64
0.5157 0.0747 7.06
0.7785 0.1394 5.21
0.5492 0.1557 6.06
0.5411 0.1884 5.68
0.6622 0.148 6.1
For each of these columns, I want to create a new column containing the quartile values. I have no problem doing it over one column at a time using this formula:
tableOne <- within(data, quartile <-
as.integer(cut(A, quantile(A, probs=0:5/5,na.rm=T))))
But as I have 100 columns
with different names, I wanted to loop over each column separately.
I tried a loop without success:
for(i in names(data)){
tableOne <- within(data, quarti <- as.integer(cut(i, quantile(i, probs=0:5/5,na.rm=T))))
}
I get the following error:
Error in cut.default(i, quantile(i, probs = 0:5/5, na.rm = T)) :
'x' must be numeric
I also tried apply function:
df.two <- lapply(df, function(x) within(data, quartile <- as.integer(cut(x, quantile(x, probs=0:5/5,na.rm=T)))))
with no success:
Error during wrapup: argument "obj" is missing, with no default
Error during wrapup: target context is not on the stack
Any advices on how to iterate my functions over all the columns and get all results in the same data.frame?
Thanks a lot