R语言中实现数据框或矩阵中字符串的批量替换
1、数据框或矩阵中字符串的批量替换
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > d[d == "d"] = "xxx" ## 将数据框中的“d”替换为“xxx” > d a b c 1 a c m 2 xxx b a 3 v a xxx 4 c xxx b
2、对指定列中的字符串进行替换
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > d[,2][d[,2] == "d"] = "xxx" ## 将第2列中的“d”替换为“xxx” > d a b c 1 a c m 2 d b a 3 v a d 4 c xxx b
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > for (i in c(1,3)) { ## 将1和3列中的“d”替换为“xxx” + d[,i][d[,i] == "d"] = "xxx" + } > d a b c 1 a c m 2 xxx b a 3 v a xxx 4 c d b
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > d[,c(1,3)][d[,c(1,3)] == "d"] = "xxx" ## 将1、3列中的“d”替换为“xxx” > d a b c 1 a c m 2 xxx b a 3 v a xxx 4 c d b
3、对指定行中的字符串进行替换
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > d[3,][d[3,] == "d"] = "xxx" ## 将第3行中的“d”替换为“xxx” > d a b c 1 a c m 2 d b a 3 v a xxx 4 c d b
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > for (i in c(2,4)) { ## 利用for循环将2,4行中的“d”替换为“xxx” + d[i,][d[i,] == "d"] = "xxx" + } > d a b c 1 a c m 2 xxx b a 3 v a d 4 c xxx b
> a <- c("a","d", "v", "c") > b <- c("c", "b", "a", "d") > c <- c("m", "a", "d", "b") > d <- data.frame(a, b, c) > d a b c 1 a c m 2 d b a 3 v a d 4 c d b > d[c(2,4),][d[c(2,4),] == "d"] = "xxx" ## 将2,4行中的“d”替换我“xxx” > d a b c 1 a c m 2 xxx b a 3 v a d 4 c xxx b