df <- as.data.frame(matrix(1:5, rep(10), ncol = 10))
This is my example data frame. I'd like to apply the following to all even values: take -6 and then compute the absolute value.
The result should look like that:
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 1 1 1 1 1 1 1 1 1 1
2 4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3
4 2 2 2 2 2 2 2 2 2 2
5 5 5 5 5 5 5 5 5 5 5
6 1 1 1 1 1 1 1 1 1 1
7 4 4 4 4 4 4 4 4 4 4
8 3 3 3 3 3 3 3 3 3 3
9 2 2 2 2 2 2 2 2 2 2
10 5 5 5 5 5 5 5 5 5 5
You could also say replace all the 2s by 4s and vice versa....
I tried to filter() out all the evens and then do -6 and abs(), tried a for loop as well and an if else function... It didn't work out the way I wanted and got far too complicated
CodePudding user response:
We could directly apply the function as these are vectorized
df[!df %%2] <- abs(df[!df %%2]-6)
-output
> df
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 1 1 1 1 1 1 1 1 1 1
2 4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3
4 2 2 2 2 2 2 2 2 2 2
5 5 5 5 5 5 5 5 5 5 5
6 1 1 1 1 1 1 1 1 1 1
7 4 4 4 4 4 4 4 4 4 4
8 3 3 3 3 3 3 3 3 3 3
9 2 2 2 2 2 2 2 2 2 2
10 5 5 5 5 5 5 5 5 5 5
CodePudding user response:
You could use ifelse
inside an lapply
, and write the resultant list back into the data frame:
df <- as.data.frame(matrix(1:5, rep(10), ncol = 10))
df[] <- lapply(df, function(x) ifelse(x %% 2 == 0, abs(x - 6), x))
df
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#> 1 1 1 1 1 1 1 1 1 1 1
#> 2 4 4 4 4 4 4 4 4 4 4
#> 3 3 3 3 3 3 3 3 3 3 3
#> 4 2 2 2 2 2 2 2 2 2 2
#> 5 5 5 5 5 5 5 5 5 5 5
#> 6 1 1 1 1 1 1 1 1 1 1
#> 7 4 4 4 4 4 4 4 4 4 4
#> 8 3 3 3 3 3 3 3 3 3 3
#> 9 2 2 2 2 2 2 2 2 2 2
#> 10 5 5 5 5 5 5 5 5 5 5
Created on 2022-11-05 with reprex v2.0.2