I have the following problem:
levelsvar <- c("arrears", "expenses", "warmhome", "telephone", "colorTV", "washer", "car", "meatfish", "holiday")
variables <- NULL
for (i in 1:length(levelsvar)) {
variables <- sapply(levelstest, function(x) (length(test$levelsvar[i][test$country==x & test$levelsvar[i]=="1"]) + length(test$levelsvar[i][test$country==x & test$levelsvar[i]=="2"])) / length(test$levelsvar[i][test$country==x]))
}
I want to use a for loop to perform the function you can see above 9 times for all the levels of "levelsvar". I tried it various times but I failed. I think the problem is that r reads
test$"arrears"
instead of
test$arrears
I already tried to use noquote() but it didn't help.
Do you have a solution to this problem?
Thank you in advance!
edit:
with example
levelstest <- c("AT", "BE")
levelsvar <- c("arrears", "expenses", "warmhome", "telephone", "colorTV", "washer", "car", "meatfish", "holiday")
structure(list(country = c("AT", "AT", "AT", "BE", "BE", "BE"
), arrears = c(1L, 1L, 1L, 2L, 1L, 1L), expenses = c(3L, 1L,
3L, 1L, 1L, 2L), warmhome = c(1L, 2L, 2L, 1L, 1L, 1L), telephone = c(4L,
1L, 4L, 4L, 3L, 3L), colorTV = c(2L, 1L, 3L, 4L, 3L, 1L), washer = c(4L,
1L, 3L, 3L, 1L, 2L), car = c(4L, 4L, 4L, 4L, 3L, 2L), meatfish = c(2L,
1L, 1L, 4L, 1L, 1L), holiday = c(2L, 2L, 1L, 3L, 4L, 2L)), .Names = c("country",
"arrears", "expenses", "warmhome", "telephone", "colorTV", "washer",
"car", "meatfish", "holiday"), row.names = c(NA, 6L), class = "data.frame")
Now I tried
variables <- NULL
for (i in 1:length(levelsvar)) {
variables <- sapply(levelstest, function(x) (length(test[levelsvar[i]][test$country==x & test[levelsvar[i]]=="1"]) + length(test[levelsvar[i]][test$country==x & test[levelsvar[i]]=="2"])) / length(test[levelsvar[i]][test$country==x]))
}
but this doesn't work.