Using ifelse Within apply

前端 未结 2 1080
忘了有多久
忘了有多久 2021-02-14 11:54

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

2条回答
  •  离开以前
    2021-02-14 12:37

    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.

提交回复
热议问题