R语言中依据列名提取列
1、直接依据列名提取
> a <- 1:5 > b <- letters[1:5] > c <- LETTERS[1:5] > d <- letters[6:10] > dat <- data.frame(a, b, c, d) > dat a b c d 1 1 a A f 2 2 b B g 3 3 c C h 4 4 d D i 5 5 e E j > dat[, "c"] ## 依据列名c提取列 [1] "A" "B" "C" "D" "E" > dat[,c("a", "d")] ## 提取a、d列 a d 1 1 f 2 2 g 3 3 h 4 4 i 5 5 j
2、subset实现
> a <- 1:5 > b <- letters[1:5] > c <- LETTERS[1:5] > d <- letters[6:10] > dat <- data.frame(a, b, c, d) > dat a b c d 1 1 a A f 2 2 b B g 3 3 c C h 4 4 d D i 5 5 e E j > subset(dat, select = b) ## 提取b列 b 1 a 2 b 3 c 4 d 5 e > subset(dat, select = c(a, c)) ## 提取a,c列 a c 1 1 A 2 2 B 3 3 C 4 4 D 5 5 E
3、%in%in实现
> a <- 1:5 > b <- letters[1:5] > c <- LETTERS[1:5] > d <- letters[6:10] > dat <- data.frame(a, b, c, d) > dat a b c d 1 1 a A f 2 2 b B g 3 3 c C h 4 4 d D i 5 5 e E j > dat[, colnames(dat) %in% "b"] ## 提取b列 [1] "a" "b" "c" "d" "e" > dat[, colnames(dat) %in% c("a", "c")] ## 提取a、c列 a c 1 1 A 2 2 B 3 3 C 4 4 D 5 5 E
4、grep、grepl实现
> a <- 1:5 > b <- letters[1:5] > c <- LETTERS[1:5] > d <- letters[6:10] > dat <- data.frame(a, b, c, d) > dat a b c d 1 1 a A f 2 2 b B g 3 3 c C h 4 4 d D i 5 5 e E j > dat[, grep("b", colnames(dat))] ## 提取b列 [1] "a" "b" "c" "d" "e" > dat[, grep("b|c", colnames(dat))] ## 提取b、c列 b c 1 a A 2 b B 3 c C 4 d D 5 e E > dat[, grepl("c", colnames(dat))] ## 提取c列 [1] "A" "B" "C" "D" "E" > dat[, grepl("a|c", colnames(dat))] ## 提取a、c列 a c 1 1 A 2 2 B 3 3 C 4 4 D 5 5 E