Q:

R calculated variable from integer variable - how?

I have a variable (HTB) which is an integer - it can have a value of either 1 or 2.
I have done some calaculations which have involved aggregating HTB by user name - so I know how often the user got a 1 or a 2 response
The resulting data frame therefore displays variables HTB.1 and HTB.2
I would like to calculate the percentage of HTB=2 for each user but this
results$HTBpercent<-results$HTB.2/(results$HTB.1+results$HTB.2)*100

does not work (presumably because it is really one variable)
How do I do this?

A:

You probably have something like:
df <- aggregate(c(1,1,2,2), list(c(1,2,1,2)), FUN=table)
df

#  Group.1 x.1 x.2
#1       1   1   1
#2       2   1   1

...where df$x is a matrix, like:
df$x
#     1 2
#[1,] 1 1
#[2,] 1 1

Therefore,
df$perc2 <- df$x[,"2"] / rowSums(df$x)
df

#  Group.1 x.1 x.2 perc2
#1       1   1   1   0.5
#2       2   1   1   0.5

