I am trying to make a new column in my dataset give a single output for each and every row, depending on the inputs from pre-existing columns.
In this output column, I d
Let n = length(x)
. ifelse
will return rep(NA, n)
if TRUE
otherwise rep(length(unique(x)), n)
. Therefore apply
will output a matrix. data$output <- apply(...
tries assign a matrix (your result) into a column in your data.frame
, data$output
. This is the cause of your error.
Your code will run if you just assign your output to a variable instead
out <- apply(data, 1, function(x) {ifelse(x == 0, NA, length(unique(x)))})
If you are not expecting a class(matrix)
as your output, but rather a vector, then there is something wrong with the logic of your function.