简体   繁体   English

如何基于R中的条件将单元格的值传播到其他行

[英]How to propagate value of a cell to other rows based on criteria in R

I have a data frame that looks like the following: 我有一个数据框架,如下所示:

index    A    B    correct
1        1    1    -
2        1    2    -
3        1    3    0
4        2    1    -
5        2    2    -
6        2    3    1

I would like to propagate the value of 'correct' to other rows when A matches. 当A匹配时,我想将“正确”的值传播到其他行。 Ie the desired output: 即所需的输出:

index    A    B    correct
1        1    1    0
2        1    2    0
3        1    3    0
4        2    1    1
5        2    2    1
6        2    3    1

So all the rows that has A = 1 will have the same value of correct, which is propagated from row(A=1,B=3). 因此,所有具有A = 1的行将具有相同的正确值,该值从row(A = 1,B = 3)传播。

How should I do this in R? 我应该如何在R中执行此操作? I have a big dataframe with many columns and it is seems that using loops to manipulate dataframes is not recommended in R. Any help would be greatly appreciated! 我有一个包含许多列的大数据框,似乎在R中不建议使用循环来操纵数据框。不胜感激!

 transform(A,correct=zoo::na.locf0(correct,T))
  index A B correct
1     1 1 1       0
2     2 1 2       0
3     3 1 3       0
4     4 2 1       1
5     5 2 2       1
6     6 2 3       1

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

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