2014-05-15 62 views
0

假裝我有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]' 有沒有好辦法做這個?

回答

1

你的代碼沒有工作的原因是data$list[i]應替換爲data[[list[i]]]。然而,這整個代碼可以重寫成兩行,這將使它更短,更高效。我已經改變了你的變量名這樣你就不會覆蓋listdata功能:

dat <- data.frame(a=1:3, b=1:3, c=1:3, d=c(0.3,0.4,0.2)) 
lst <- c("a", "b", "c") 
output.id <- lst 
output.metric <- sapply(lst, function(x) sum(dat[,x]*dat$d)/sum(dat[,x])) 
output.metric 
#   a   b   c 
# 0.2833333 0.2833333 0.2833333 

另一種方法是:

colSums(dat[,lst]*dat$d)/colSums(dat[,lst]) 
#   a   b   c 
# 0.2833333 0.2833333 0.2833333 
+0

如果您要改變'list','data'是也是一個基本的R功能。 – thelatemail

+0

@thelatemail謝謝 - 現在得到了那一個 – josliber

0

索引操作存在問題。您使用$運營商,在這種情況下,您應該使用[]。一般來說,你不必使用for循環來實現這一點,因爲R中的許多操作都可以被矢量化。但是你如何你可以用它做的for循環:

output.id<- numeric(length(list))  #if you have to populate a vector in a for loop, it is good practice to initialize it with the correct or expected length 
output.metric<-numeric(length(list)) 

for(i in 1:length(list)){ 

    id<-list[i] 

    #note the difference in the following line where i use [] instead of $ and id instead of list[i] 

    metric<- sum(data[,id]*data$d)/sum(data[,id]) 

    output.id[i] <- id    
    output.metric[i] <- metric 
} 

#this will create a data.frame with results 
output <- data.frame(id = output.id, metric = output.metric) 

我建議你閱讀的R教程/介紹,瞭解更多關於子集化等

相關問題