如何在R中进行条件替换?

时间:2017-07-12 16:31:28

标签: r dplyr conditional

这是R.中的一个简单的条件问题 这是一个示例数据框。 ""代表空格

>df  
    A   B  
    1   Y  
    1   N  
    ""  Y  
    0   N  
    ""  N  
    1   Y  
    0   Y  
    ""  N  
    0   Y

我正在尝试检查IF df $ B ==" Y"然后在空白处以df $ A打印1。

我试过df$A[df$A == ""] <- df$B[df$B == "Y"]
这会将所有空格更改为&#34; Y&#34;。

请帮忙!

1 个答案:

答案 0 :(得分:1)

这就是你想要的吗?

public class MainActivity extends AppCompatActivity {

    private String Student_Name = "";
    private int Student_Grade = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText studentName = (EditText) findViewById(R.id.name);
        EditText studentGrade = (EditText) findViewById(R.id.grade);
        Button Submit = (Button) findViewById(R.id.submit);
        Button Report = (Button) findViewById(R.id.report);

        final ArrayList<String> infos = new ArrayList<String>();
        final String report = "";
        final boolean Status = true;
        for(int i = 0;Status != false;i++){
            String name = studentName.getText().toString();
            String grade = studentGrade.getText().toString();
            report = name + grade;
            Submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    infos.add(report);
                }
            });
            infos.add(report);
            Report.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this,ReportActivity.class);
                    startActivity(intent);
                    Status = false;
                }
            });
        }

这是一个基础版本:

library("dplyr")
library("tibble")

df <- 
tibble::tribble(
  ~A,   ~B,
  1,  "Y",
  1,  "N",
  "",  "Y",
  0,  "N",
  "",  "N",
  1,  "Y",
  0,  "Y",
  "",  "N",
  0,  "Y")

df %>% mutate(A = ifelse(B == "Y" & A == "",1,A))
#> # A tibble: 9 x 2
#>       A     B
#>   <chr> <chr>
#> 1     1     Y
#> 2     1     N
#> 3     1     Y
#> 4     0     N
#> 5           N
#> 6     1     Y
#> 7     0     Y
#> 8           N
#> 9     0     Y