我需要遍歷數據框並計算正在循環的變量的函數。循環變量的R-ddply函數
的表例如:
table<-data.frame(num1=seq(1,10,len=20), num2=seq(20,30,len=20),
char1=c(rep('a',10), rep('b',10)),
target=c(rep(1,10), rep(0,10)))
我創建的變量列表:
nums<-colnames(table)[sapply(table, class)=='numeric']
nums<-nums[nums!='target']
而且表,我將填充:
planF<-data.frame(deciles=c(1), min=c(1), max=c(1), pos=c(1))
planF<-planF[-1,]
,循環:
library(plyr)
for (i in 1:length(nums)){
table$deciles<-ntile(table[,nums[i]],5)
plan<-ddply(table, 'deciles', summarize, min=min(nums[i]),
max=max(nums[i]),pos=sum(target))
planF<-rbind(planF,plan)
}
我需要獲取每個十分位變量por的最小值和最大值。而是我得到:
deciles min max pos
1 1 num1 num1 4
2 2 num2 num2 4
3 3 <NA> <NA> 2
4 4 <NA> <NA> 0
5 5 <NA> <NA> 0
6 1 num1 num1 4
7 2 num2 num2 4
8 3 <NA> <NA> 2
9 4 <NA> <NA> 0
10 5 <NA> <NA> 0
對於可變NUM1我需要得到的結果是:
ddply(table, 'deciles', summarize, min=min(num1),
max=max(num1),pos=sum(target))
deciles min max pos
1 5.736842 7.157895 0
2 7.631579 9.052632 0
3 1.000000 10.000000 2
4 1.947368 3.368421 4
5 3.842105 5.263158 4
而且做同樣與NUM2的結果如下。
我明白,我需要引入具有下列形式的變量:
num1
但代碼編寫
'num1'
我試着用:
min=min(as.name(nums[i]))
但我出現錯誤:
Error in min(as.name(nums[i])) : 'type' (symbol) not valid argument
我該如何計算一個正在循環變量的函數?
很難確定你正在嘗試做什麼。你能用文字解釋嗎? – MJeffryes
@MJeffryes:嗨,我需要獲得變量por的最小值和最大值。 – GabyLP
如果你也會顯示你想要的輸出,會更容易。 –