2014-05-15 3 views
0

내가 4 열 데이터 프레임, 그 열 이름의 3을 포함하는 목록을 가지고 척이 목록 항목을 참조

#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'에 따라 데이터 열을 호출하려고합니다. 그래서, 나는, 내가

metric<- sum(data$list[i]*data$d)/sum(data$list[i]) 

'는'

로 대체

metric<- sum(data$a*data$d)/sum(data$a) 

곳 '목록 [i]를'로 해석 할 = 때를하는 좋은 방법이 있나요 이 작업을 수행?

답변

1

코드가 작동하지 않는 이유는 등의 부분 집합에 대한 자세한 내용을 보려면하는 R 튜토리얼/소개를 읽으십시오 data$list[i]data[[list[i]]]으로 대체되어야합니다. 그러나이 전체 코드는 두 줄로 다시 작성할 수 있으므로 더 짧고 효율적입니다.

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'는 당신이 listdata 기능을 덮어 쓰기하지 않는, 그래서 나는 당신의 변수 이름을 변경했습니다 또한 기본 R 함수. – thelatemail

+0

감사 메일 - 감사합니다. – josliber

0

색인 생성 작업에 문제가 있습니다. $ 연산자를 사용합니다.이 경우 []을 사용해야합니다. 일반적으로, R의 많은 연산이 벡터화 될 수 있기 때문에 for 루프를 사용하여이 작업을 수행하지 않아도됩니다. 그러나 당신을 보여주기 위해 당신이 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) 

을 당신이