简体   繁体   English

r 找到带有过滤器的行然后替换单个单元格值

[英]r find a row with filter then replace single cell value

I have data in the following format:我有以下格式的数据:

        col1   col2  col3  col4
row1     xx    100    ABC
row2     xx    10     ABC
row3     xx    100    BYZ

And need to find a specific value by multiple conditions and multiply it.并且需要通过多个条件找到一个特定的值并将其相乘。 I wish to take the 10 value in col2 and row2 and multiply it by 100.我希望将 col2 和 row2 中的 10 值乘以 100。

The data frame is too large and will change with each refresh so the problematic value must be found by searching for conditions.数据框太大,每次刷新都会改变,所以必须通过搜索条件来找到有问题的值。

The code I have used to find our desired value is:我用来查找所需值的代码是:

dplyr::filter(data, col3 == 'ABC' & col1 == 'xx')[2]

But attempting to re-assign this like so:但是尝试像这样重新分配:

dplyr::filter(data, col3 == 'ABC' & col1 == 'xx)[2]
<- dplyr::filter(data, col3 == 'ABC' & col1 == 'xx')[2]
 * 100

Is met with a new error that filter()<- is not a subset function of dplyr.遇到一个新错误,即 filter()<- 不是 dplyr 的子集函数。

I tried reverting back to an earlier version of dplyr without improvement.我尝试恢复到 dplyr 的早期版本而没有改进。

You can use simple ifelse to change the values in col2 for specific conditions.您可以使用简单的ifelse为特定条件更改col2的值。

library(dplyr)
data %>% mutate(col2 = ifelse(col3 == 'ABC' & col1 == 'xx', col2 * 100, col2))

Or keeping it in base :或将其保存在 base 中:

transform(df, col2 = ifelse(col3 == 'ABC' & col1 == 'xx', col2 * 100, col2))

Also there is no filter<- function defined so you can't use it directly.也没有定义filter<-函数,所以你不能直接使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM