假裝我有4列的數據幀,以及包含這些列名的清單3R中調用從數據幀的矢量時參照的列表項
#create data with 4 columns, a-d
a<-c(1,2,3)
b<-c(1,2,3)
c<-c(1,2,3)
d<-c(0.3,0.4,0.2)
data<-data.frame(a,b,c,d)
#create a list that doesnt include d
list<-c('a','b','c')
我想要運行一個循環我在那裏根據這些列的總和計算值,每次一個,然後將這些信息存儲爲一張表格,該表格給出了每個處理過的列的ID以及計算的值。
以下是我已經嘗試:
#make output vectors for a loop
output.id<-c()
output.metric<-c()
#run loop
for(i in 1:length(list)){
#name of which id in the list you are working on
id<-list[i]
#compute something based on the data contained within a vector of the data frame, referencing where you are in the list
metric<- sum(data$list[i]*data$d)/sum(data$list[i])
#save the name of which id you were working on and the computed value for each element i
output.id<-c(output.id,id)
output.metric<-(output.metric,metric)
}
問題是度量的計算。我想根據我正在處理的列表項「i」調用一列數據。所以,當i = A,我想
metric<- sum(data$list[i]*data$d)/sum(data$list[i])
被解釋爲被替換爲 'A'
metric<- sum(data$a*data$d)/sum(data$a)
其中 '名單[I]' 有沒有好辦法做這個?
如果您要改變'list','data'是也是一個基本的R功能。 – thelatemail
@thelatemail謝謝 - 現在得到了那一個 – josliber