Can you execute 2 commands using a single R code?

I would want to use the subset and na.omit command in one singular R code on an imported dataset and save the data into a new dataset.

I tried using ";" to seperate the 2 commands but it didnt work.

I was wondering how can it be done?

Welcome to the community!

First of all, this is a bad idea. Why do you want to do that? What benefit will you get from this?

Second, if you want to do, you can do na.omit(subset(<the relevant code for subsetting in your use case>)). I can't test, but it should work.

Third, use of ;'s is not encouraged. As pointed out by jcblum earlier, here are some references:

  1. https://style.tidyverse.org/syntax.html#semicolons
  2. https://irudnyts.github.io//r-coding-style-guide/

You can also do this with the pipe operator, %>%, from the magrittr package.

library(magrittr)
DF <- data.frame(Name = LETTERS[1:5], Value = c(1,2,NA,4,5))
DF
#>   Name Value
#> 1    A     1
#> 2    B     2
#> 3    C    NA
#> 4    D     4
#> 5    E     5
DF_New <- DF %>% na.omit() %>% subset(Value > 1 & Value < 5)
DF_New
#>   Name Value
#> 2    B     2
#> 4    D     4

Created on 2019-09-29 by the reprex package (v0.2.1)

Hi Yarnabrina,

Thanks for the responds! I am doing data cleaning for my dataset at the moment.

Would it be better, and simpler way that could help rectified errors, just create 3 codes to:

(1) subset inaccurate data;
(2) na.omit;
(3) save as a new df?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.