DeltaIV - 2 months ago 6x

R Question

Sample df:

`df <- data.frame(x = c(runif(10,0,2*pi),runif(10,0,360)), group = gl(n = 2, k = 10, labels =c("A","B")))`

I want to modify

`x`

`A`

`base`

`df <- within(df,x[group == "A"] <- x[group == "A"]*180/pi)`

I was wondering if there could be a way to do this with

`dplyr`

`df <- df %>% filter(group == "A") %>% mutate(x = x*180/pi)`

Because it returns only the subset of

`df`

`group == "A"`

`base`

`dplyr`

Answer

We can use `ifelse`

to create the logical condition, and based on that we either do the arithmetic calculation or `else`

return the original values.

```
df %>%
mutate(x = ifelse(group=="A", x*180/pi, x))
```

Or as @AlexIoannides mentioned, `if_else`

from `dplyr`

can be used so as the `type`

should be taken care of.

In `data.table`

, this can be done by assignment in place and should be more efficient.

```
library(data.table)
setDT(df)[group=="A", x := x*180/pi]
```

Source (Stackoverflow)

Comments