Extracting and replacing elements of a vector¶
x <- c(10, 12, 30, 14, 50)
x[1]
[1] 10
x[5]
[1] 50
x[c(2,4,6)]
[1] 12 14 NA
x[c(1,1,1,2,2)]
[1] 10 10 10 12 12
x[-c(1,3,5)]
[1] 12 14
x[c(FALSE,TRUE,FALSE,TRUE,FALSE)]
[1] 12 14
x[x>=20]
[1] 30 50
names(x) <- c("a","b","c","d","e")
x[c("a","c")]
a c
10 30
set.seed(231)
y <- rnorm(n=12)
y[1:4] <- 0
y
[1] 0.00000000 0.00000000 0.00000000 0.00000000 -0.47335746 0.21739728
[7] 0.06292205 -0.87782986 0.56368979 -0.03432728 -0.22631292 1.38657787
y <- rnorm(n=12)
y[y < 0] <- 0
y
[1] 0.0000000 0.0000000 1.4013312 0.3196224 1.0058453 0.0000000 0.0000000
[8] 1.6502536 1.4374338 0.0000000 0.0000000 0.0000000
- R file: extracting-and-replacing-elements.R
- Rmarkdown file: extracting-and-replacing-elements.Rmd
- Jupyter notebook file: extracting-and-replacing-elements.ipynb
- Interactive version of the Jupyter notebook (shuts down after 60s):
- Interactive version of the Jupyter notebook (sign in required):