This produces the identical result to your code, and does not use loops.
set.seed(1) # need reproducible sample data
owner <-c("Fred", "Mary", "James", "Ingrid", "Schubert", "Alice") #owner names
animal <-c("Cow", "Giant sheep", "Deer", "Giga chicken") #Animal types
data <- data.frame(owner= sample(owner, 1000, replace= TRUE),
animal=sample(animal, 1000, replace= TRUE),
weight=rnorm(1000,mean=250, sd=50)) #data set
# note the column names in sub.set
sub.set <- data.frame(owner=c("James","Alice", "Schubert"),
animal=c("Deer","Giga chicken", "Deer"),
count=c(0,0,1))
# this is the code to exclude rows where there are no animals left
data <- merge(data,sub.set,by=c("owner","animal"),all.x=T)
data <- with(data,data[count!=0 | is.na(count),])
data <- data[,-4]
xtab.2 <- xtabs(weight~.,data)
This code merges data
and sub.set
on the columns owner
and animal
to create a new column count
. Then it includes only rows where count!=0
or !is.na(count)
. Then it removes the count
column and calculates the cross tab as before.