Svalf Svalf - 16 days ago 6
R Question

In R: Dataframes in nested for loop. <0 rows> (or 0-length row.names) error

This is a subset of the data frame I am working on:


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



It consists of 5 subjects, for whom there is information on 3 fruits and 3 vegetables:


  • 1 = the subject does not eat the fruit/vegetable

  • 2 = the subject eats the fruit/vegetable



I am interested in counting how many individuals eat the 9 possible combinations of fruits and vegetables (FRUIT1 with VEG1, FRUIT1 with VEG2, …).
This is the script I wrote:

# 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: the script above works outside the for loops but in this nested for loops I get the following message:
<0 rows> (or 0-length row.names)
for PP, AA, PA and AP. Why are the sub-datasets (PP, AA, PA and AP) empty in this case?

Answer

You need to change to PP <- dataframe[dataframe[[fruit]] == '2' & dataframe[[veg]] == '2',] and the others as well, fruit is a string and dataframe$fruit is not a column

Comments