R I()


I() function changes the class of an object to indicate that it should be treated ‘as is’.


For a formula, it is used to inhibit the interpretation of operators such as "+", "-", "*" and "^" as formula operators, so they are used as arithmetical operators. This is interpreted as a symbol by terms.formula.

> x <- c(rep(1:20))
> y <- x * 2
> lm (y ~ I(x + 1))
Call:
lm(formula = y ~ I(x + 1))
Coefficients:
(Intercept)     I(x + 1)
-2            2


In function data.frame, I() inhibits the conversion of character vectors to factors and the dropping of names, and ensures that matrices are inserted as single columns. I() can also be used to protect objects which are to be added to a data frame, or converted to a data frame via as.data.frame.

> df <- cbind(as.data.frame(1:10), I(letters[1:10]))
> colnames(df) <- c("number", "letter")
> str(df)
'data.frame':   10 obs. of  2 variables:
$ number: int  1 2 3 4 5 6 7 8 9 10
$ letter: 'AsIs' chr  "a" "b" "c" "d" ...
> df2 <- cbind(as.data.frame(1:10), letters[1:10])
> str(df2)
'data.frame':   10 obs. of  2 variables:
$ 1:10         : int  1 2 3 4 5 6 7 8 9 10
$ letters[1:10]: chr  "a" "b" "c" "d" ...







endmemo.com © 2024  | Terms of Use | Privacy | Home