如果一行中有任何列满足条件,则mutate()列除外 [英] If any column in a row meets condition than mutate() column

查看:92
本文介绍了如果一行中有任何列满足条件,则mutate()列除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用dplyr,试图使用ifelse和mutate有条件地更新列中的值。我想说的是,在数据帧中,如果一行中的任何变量(列)等于7,则变量c应该变为100,否则c保持不变。

Using dplyr, I am trying to conditionally update values in a column using ifelse and mutate. I am trying to say that, in a data frame, if any variable (column) in a row is equal to 7, then variable c should become 100, otherwise c remains the same.

df <- data.frame(a = c(1,2,3),
                 b = c(1,7,3),
                 c = c(5,2,9))

df <- df %>%  mutate(c = ifelse(any(vars(everything()) == 7), 100, c))

这给了我错误:

Error in mutate_impl(.data, dots) : 
  Evaluation error: (list) object cannot be coerced to type 'double'.

我想要的输出是:

  a b   c
1 1 1   5
2 2 7 100
3 3 3   9

注意:这是具有更多行和列的较大数据集的抽象示例。

Note: this is an abstract example of a larger data set with more rows and columns.

编辑:
此代码使我更接近一点,但是它并不适用每一行的ifelse语句。相反,如果数据帧中的任何位置存在7,它将在c列中将所有值更改为100。

This code gets me a bit closer, but it does not apply the ifelse statement by each row. Instead, it is changing all values to 100 in column c if 7 is present anywhere in the data frame.

df <- df %>%  mutate(c = ifelse(any(select(., everything()) == 7), 100, c))

  a b   c
1 1 1 100
2 2 7 100
3 3 3 100

也许这是不可能做到的dplyr?

Perhaps this is not possible to do using dplyr?

推荐答案

我认为这应该可行。我们可以检查 df 中的值是否等于7。之后,使用 rowSums 查看是否有大于0的行。 ,这意味着至少有一个值为7。

I think this should work. We can check if values in df equal to 7. After that, use rowSums to see if any rows larger than 0, which means there is at least one value is 7.

df <- df %>% mutate(c = ifelse(rowSums(df == 7) > 0, 100, c))

或者我们可以使用apply

Or we can use apply

df <- df %>% mutate(c = ifelse(apply(df == 7, 1, any), 100, c))

等价的基本R就是这样。

A base R equivalent is like this.

df$c[apply(df == 7, 1, any)] <- 100

这篇关于如果一行中有任何列满足条件,则mutate()列除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆