Tlatwork
Tlatwork

Reputation: 1525

Use pipes in R to set data

Is it possible to use the pipe Operator in R (not to get) but to set data?

Lets say i want to modify the first row of mtcars dataset and set the value of qsec to 99.

Traditional way:

mtcars[1, 7] <- 99

Is that also possible using the pipe Operator?

mtcars %>% filter(qsec == 16.46) %>% select(qsec) <- 99

Upvotes: 0

Views: 94

Answers (1)

akrun
akrun

Reputation: 887831

If we are in a state where the chain is absolute necessary or curious to know whether <- can be applied in a chain

library(magrittr)
mtcars %>% 
    `[<-`(1, 7, 99) %>%
     head(2)
#              mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4      21   6  160 110  3.9 2.620 99.00  0  1    4    4
#Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4

Also, inset (from the comments) is an alias for [<-

mtcars %>% 
   inset(1, 7, 99) %>%
   head(2)

Upvotes: 3

Related Questions