2016-11-17 204 views
-1

這是數據幀的一個子集我的工作:嵌套for循環中的數據幀。 <0 rows>(或0長度row.names)錯誤

ID FRUIT1 FRUIT2 FRUIT3 VEG1 VEG2 VEG3 
1  1  2  2  1  2  2 
2  2  1  1  1  1  1 
3  2  1  2  1  2  2 
4  2  2  2  1  2  1 
5  1  1  1  2  1  2 

它由5名受試者的,對他們來說,有3信息水果和蔬菜3:

  • 1 =受試者沒有吃水果/蔬菜
  • 2 =受試者吃水果/蔬菜

我有興趣計算有多少人吃了9種可能的水果和蔬菜組合(FRUIT1與VEG1,FRUIT1與VEG2,...)。 這是我寫的劇本:

# Read data 
dataframe <- read.csv("myfile.csv", header=TRUE) 

# Define variables 
FRUIT= names(dataframe)[2:4]) 
VEG= names(dataframe[5:7])) 

# Check frequency of interactions 
for (fruit in FRUIT) { 
    for (veg in VEG) { 
     #Double-positive: keep only subjects that each both the fruit and the vegetable 
     PP <- dataframe[dataframe$fruit=='2' & dataframe$veg=='2',] 
     #Double-negative: keep only subjects that don’t eat any 
     AA <- dataframe[dataframe$fruit=='1' & dataframe$veg=='1',] 
     #Only FRUIT-positive: keep only subjects that eat the fruit, but not the vegetable 
     PA <- dataframe[dataframe$fruit=='2' & dataframe$veg=='1',] 
     #Only VEG-positive: keep only the subject that eat the vegetable, but not the fruit 
     AP <- dataframe[dataframe$fruit=='1' & dataframe$veg=='2',] 
     # Print the name of the fruit, the vegetable, and the counts of each of the 4 categories 
    toprint <- c(kir,hla,nrow(PP),nrow(AP),nrow(PA),nrow(AA)) 
    setwd(「~/Directory/「) 
    write(toprint, file = "NumberIndividuals.csv",ncolumns=6,append = TRUE, sep = " ") 
    } 
} 

問題<0 rows> (or 0-length row.names)用於PP,AA,PA和AP:上面的for循環,但在此之外嵌套作品環路我收到以下消息腳本。爲什麼在這種情況下子數據集(PP,AA,PA和AP)是空的?

+0

你需要做'PP < - dataframe [dataframe [[fruit]] =='2'&dataframe [[veg]] =='2',]'etc,dataframe $ fruit不是列 –

+0

有一個關閉'''在計算'FRUIT'和'VEG'時太多了 – Acarbalacar

回答

1

您需要更改爲PP <- dataframe[dataframe[[fruit]] == '2' & dataframe[[veg]] == '2',]和其他人也,果是一個字符串和數據幀$果不其列

3

你可以試試這個沒有明確的for循環:

combos<-expand.grid(fruit=grep("FRUIT",colnames(dataframe),value=TRUE), 
        veg=grep("VEG",colnames(dataframe),value=TRUE), 
        stringsAsFactors=FALSE) 
counts<-apply(combos,1,function(x) sum(rowSums(dataframe[,x]==2)==2)) 
cbind(combos,counts=counts) 
# fruit veg counts 
#1 FRUIT1 VEG1  0 
#2 FRUIT2 VEG1  0 
#3 FRUIT3 VEG1  0 
#4 FRUIT1 VEG2  2 
#5 FRUIT2 VEG2  2 
#6 FRUIT3 VEG2  3 
#7 FRUIT1 VEG3  1 
#8 FRUIT2 VEG3  1 
#9 FRUIT3 VEG3  2