[R] Is it odd or not? about I() function
Hiroto Miyoshi
h|roto-m|yo@h| @end|ng |rom e-m@||@jp
Sat Apr 19 03:46:39 CEST 2025
Dear R expert
I encountered a bewildering situation, about which
I am seeking help. I wrote a following toy script
which can recreate the situation.
--- the script begins here ---
1 │ library(tidyverse)
2 │ library(rlist)
3 │ library(patchwork)
4 │ set.seed(42)
5 │ f <- function(x, y, z, x_axis) {
6 │ rslt_with_I <- I(x^2 * 0.5) + I(x * y)
7 │ rslt_without_I <- (x^2 * 0.5) + (x * y)
8 │ out <- data.frame(rslt_without_I, rslt_with_I)
9 │ return(out)
10 │ }
11 │
12 │ df <- data.frame(
13 │ x = runif(40, 0, 1),
14 │ y = runif(40, 0, 1),
15 │ z = rep(1:4, rep(10, 4)),
16 │ x_axis = rep(1:10, 4)
17 │ )
18 │
19 │ dta <- pmap(df, f) %>%
20 │ list.stack(.) %>%
21 │ cbind(df, .)
22 │
23 │ g1 <- ggplot(dta, aes(x = x_axis, y = rslt_with_I, color =
factor(z))) +
24 │ geom_point() +
25 │ geom_line()
26 │ g2 <- ggplot(dta, aes(x = x_axis, y = rslt_without_I, color =
factor(z))) +
27 │ geom_point() +
28 │ geom_line()
29 │
30 │ g <- g1 | g2
31 │ plot(g)
32 │
33 │ dta$rslt_with_I == dta$rslt_without_I
34 │ # the end of the script
The two graphs, i.e. g1 and g2 are different and obviously, the data do not
fit in the graph area for g1. The command "dta$rslt_with_I ==
dta$rslt_without_I"
shows the plotted data are identical. I want why this happens.
Sincerely
Hiroto
[[alternative HTML version deleted]]
More information about the R-help
mailing list