mutate_if for all numeric columns in mixed data frame

Hi - I'm running into an issue when I use mutate_if in a mixed data frame, where it stops at the first FALSE occurrence:

g <- DF %>%
mutate_if(is.numeric, funs(. / Marker_2+))

My large data frame looks something like this:

colnames = Marker_1+, Marker_2+, ..., Categorial_info, Character_info,..., Marker_3+, Marker_4+
where Marker columns are integers and all else are factors. When I run the above script, I get the expected result for the first Marker_1 and Marker_2, but it Marker_3 and Marker_4 are left unchanged. It appears mutate stops at the first FALSE given by is.numeric. Any help would be much appreciated.

I'm using tidyverse 1.2.1

I think the problem is that you have divided the column Marker_2+ by itself, changing it to all 1's, so any column processed after that is unchanged. Below you can see that mutate_if does process every column when the function is to add 100. Dividing by column B also works, but columns E and F do not change in value because B = 1 in all cases.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df <- data.frame(A = 1:8, B = 2:9, C = LETTERS[1:8], D = LETTERS[2:9], E = 3:10, F = 4:11)
df
#>   A B C D  E  F
#> 1 1 2 A B  3  4
#> 2 2 3 B C  4  5
#> 3 3 4 C D  5  6
#> 4 4 5 D E  6  7
#> 5 5 6 E F  7  8
#> 6 6 7 F G  8  9
#> 7 7 8 G H  9 10
#> 8 8 9 H I 10 11

g <- df %>% mutate_if(is.numeric, funs(. + 100))
g
#>     A   B C D   E   F
#> 1 101 102 A B 103 104
#> 2 102 103 B C 104 105
#> 3 103 104 C D 105 106
#> 4 104 105 D E 106 107
#> 5 105 106 E F 107 108
#> 6 106 107 F G 108 109
#> 7 107 108 G H 109 110
#> 8 108 109 H I 110 111

g2 <- df %>% mutate_if(is.numeric, funs(./B))
g2
#>           A B C D  E  F
#> 1 0.5000000 1 A B  3  4
#> 2 0.6666667 1 B C  4  5
#> 3 0.7500000 1 C D  5  6
#> 4 0.8000000 1 D E  6  7
#> 5 0.8333333 1 E F  7  8
#> 6 0.8571429 1 F G  8  9
#> 7 0.8750000 1 G H  9 10
#> 8 0.8888889 1 H I 10 11

Created on 2019-06-05 by the reprex package (v0.2.1)

2 Likes

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