【发布时间】:2015-12-15 16:24:43
【问题描述】:
我在R 中有一个data.frame,它包含许多带有数值的列。
像这样:
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
对于这些列中的每一列,我想创建一个包含四分位值的新列。使用此公式一次处理一列没有问题:
tableOne <- within(data, quartile <-
as.integer(cut(A, quantile(A, probs=0:5/5,na.rm=T))))
但由于 100 columns 的名称不同,我想分别循环遍历每一列。
我尝试了一个循环但没有成功:
for(i in names(data)){
tableOne <- within(data, quarti <- as.integer(cut(i, quantile(i, probs=0:5/5,na.rm=T))))
}
我收到以下错误:
Error in cut.default(i, quantile(i, probs = 0:5/5, na.rm = T)) :
'x' must be numeric
我也试过应用函数:
df.two <- lapply(df, function(x) within(data, quartile <- as.integer(cut(x, quantile(x, probs=0:5/5,na.rm=T)))))
没有成功:
Error during wrapup: argument "obj" is missing, with no default
Error during wrapup: target context is not on the stack
关于如何在所有列上迭代我的函数并在同一 data.frame 中获取所有结果的任何建议?
非常感谢
【问题讨论】:
-
创建一个函数(以向量为参数)并使用
lapply。 -
我试过 apply 但我并不比循环更好!
-
df.two <- lapply(data, function(x) within(data, quartile <- as.integer(cut(x, quantile(x, probs=0:5/5,na.rm=T))))) -
也许,
cbind(df, lapply(df, function(x) as.integer(cut(x, quantile(x, probs=0:5/5,na.rm=T))))),但我无法测试,因为您没有提供可重现的示例。 -
您的示例数据集不需要超过 3 列,可能需要 10 行。