在应用中使用ifelse [英] Using ifelse Within apply
问题描述
我正在尝试使数据集中的新列为每一行提供单个输出,具体取决于现有列的输入.
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.
在此输出列中,如果给定行中的任何输入值都为"0",我希望为"". 否则(如果所有输入都不为0),我希望该行的输出为输入的唯一值的数量.
In this output column, I desire "NA" if any of the input vales in a given row are "0". Otherwise (if none of the inputs are 0), I want the output for that row to be the number of unique values of the inputs.
我认为该解决方案将使用嵌套在 apply 函数中的 ifelse 函数,但是出现一个我不理解的错误.
I thought that the solution would use an ifelse function nested within an apply function, but I get an error that I do not understand.
data$output <- apply(data, 1, function(x) {ifelse(x == 0, NA, length(unique(x)))})
$<-.data.frame
(*tmp*
,输出",值= c(3L,3L,3L,3L,: 替换有3行,数据有4
Error in
$<-.data.frame
(*tmp*
, "output", value = c(3L, 3L, 3L, 3L, : replacement has 3 rows, data has 4
我不知道替换为什么有3行,因为我认为对4行中的每行都执行相同的功能.
I do not know why the replacement has 3 rows, as I thought apply just does the same function to each of my 4 rows.
推荐答案
您要检查行中是否有任何变量为0,因此需要在ifelse
中使用any(x==0)
而不是x == 0
声明:
You want to check if any of the variables in a row are 0, so you need to use any(x==0)
instead of x == 0
in the ifelse
statement:
apply(data, 1, function(x) {ifelse(any(x == 0), NA, length(unique(x)))})
# [1] 1 NA 2
基本上,如果ifelse
的第一个参数的长度为n,则返回长度为n的向量.您希望每行一个值,但是要用x==0
传递多个值(您传递的值的数量等于数据框中的列数).
Basically ifelse
returns a vector of length n if its first argument is of length n. You want one value per row, but are passing more than one with x==0
(the number of values you're passing is equal to the number of columns in your data frame).
数据:
(data <- data.frame(a=c(1, 2, 3), b=c(1, 0, 1)))
# a b
# 1 1 1
# 2 2 0
# 3 3 1
这篇关于在应用中使用ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!