2016-11-17 3 views
-1

Dies ist eine Teilmenge des Datenrahmens auf Ich arbeite:Datenrahmen in verschachtelter Schleife. <0 rows> (oder 0-Länge row.names) Fehler

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 

Es von 5 Probanden besteht, für den gibt es Informationen über 3 Obst und Gemüse 3:

  • 1 = das Thema nicht isst das Obst/Gemüse
  • 2 = isst das Subjekt das Obst/Gemüse

Ich bin interessiert zu zählen, wie viele Individuen die 9 möglichen Kombinationen von Obst und Gemüse essen (FRUIT1 mit VEG1, FRUIT1 mit VEG2, ...). Dies ist das Skript schrieb ich:

# 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 = " ") 
    } 
} 

Problem: das Skript oben genannten Arbeiten außerhalb der for-Schleifen, aber in diesem verschachtelten for-Schleifen uns die folgende Meldung: <0 rows> (or 0-length row.names) für PP, AA, PA und AP. Warum sind die Sub-Datensätze (PP, AA, PA und AP) in diesem Fall leer?

+0

Sie müssen do 'PP <- Dataframe [Dataframe [[Frucht]] == '2' & Dataframe [[veg]] == '2',]' etc, Dataframe $ fruit ist keine Spalte –

+0

Es gibt ein Closing ')' zu viel in Ihrer Berechnung von 'FRUIT' und' VEG' – Acarbalacar

Antwort

1

Sie müssen auch zu PP <- dataframe[dataframe[[fruit]] == '2' & dataframe[[veg]] == '2',] und die anderen ändern, Obst ist ein String und Datenrahmen $ Frucht ist nicht eine Spalte

3

Sie können versuchen, diese ohne explizite for Schleifen:

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 
Verwandte Themen