mtcars is a built-in dataset in R. Only first 3 rows and first column are returned, in cars. The drop argument is given as FALSE, so a vector is not returned.
If you extract a column, etc, you are always creating new objects in R. Any changes on the new object do not affect the original object. While this might seem to lead to easier programming, it also makes R more memory intensive.
# ex14.R
# get only 3 row and 2 columns
cars <- mtcars[1:3,1,drop = FALSE]
cat("Original cars =\n")
print(cars)
mpg <- cars["mpg"]
cat("\nOriginal mpg =\n")
print(mpg)
mpg[1] <- 42
cat("\nModified mpg =\n")
print(mpg)
cat("\nMazda RX4 mpg is not modified\n")
cat("as mpg is a copy\n")
print(cars)
# Original cars =
# mpg
# Mazda RX4 21.0
# Mazda RX4 Wag 21.0
# Datsun 710 22.8
#
# Original mpg =
# mpg
# Mazda RX4 21.0
# Mazda RX4 Wag 21.0
# Datsun 710 22.8
#
# Modified mpg =
# mpg
# Mazda RX4 42
# Mazda RX4 Wag 42
# Datsun 710 42
#
# Mazda RX4 mpg is not modified
# as mpg is a copy
# mpg
# Mazda RX4 21.0
# Mazda RX4 Wag 21.0
# Datsun 710 22.8
No comments:
Post a Comment