ed_error is a dataframe with two columns. I want to go through all rows one by one and add 1 to the variable I created, only if the string name of the value in the first column is equal to "general" and the integer value of the second column is equal to 1.
This is how the data looks like.
The code:
general_list <- 0
for (row in 1:nrow(ed_error)) {
if (ed_error[row, 1] == "general") && (ed_error[row, 2] == 1) {
general_list <- general_list 1 }
}
The error:
Error in parse(text = x, srcfile = src):
5: for (row in 1:nrow(ed_error)) {
6: if (ed_error[row, 1] == "general") &&
^
CodePudding user response:
In R, most of the things would not require explicit for
loops. This comparison can be done in vectorized way and use sum
to count how many times the condition is satisfied.
general_list <- sum(ed_error$education == "general" & ed_error$error == 1)
If there are NA
values in the data you may add na.rm = TRUE
in sum
.
CodePudding user response:
The )
for if
ends before the &&
if (ed_error[row, 1] == "general")
i.e.
> if('a' == 'b') && ('c' == 'd')
Error: unexpected '&&' in "if('a' == 'b') &&"
Instead it would be
general_list <- 0
for (row in 1:nrow(ed_error)) {
if(ed_error[[1]][row] == "general" && ed_error[[2]][row] == 1) {
general_list <- general_list 1
}
}
We may also use a vectorized option
general_list <- with(ed_error, sum(education %in% 'general' & error %in% 1))