更改列名称和值

时间:2015-07-22 13:52:22

标签: r

给出以下数据框:

> df
     A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3
[1,]  0  0    0    0  0  0  0    0    0  0
[2,]  0  0    0    0  0  0  0    0    0  0

我试图将列名中的所有“2.1”替换为“aa”,并用数字1替换这些列中的所有值。这样:

     A1 A2 A aa A2.2 A3 B1 B2 B aa B2.2 B3
[1,]  0  0    1    0  0  0  0    1    0  0
[2,]  0  0    1    0  0  0  0    1    0  0

我怎样才能做到这一点?

非常感谢提前。

5 个答案:

答案 0 :(得分:2)

你可以尝试:

library(dplyr)
df %>% 
  mutate_each(funs(sub(".*.", 1, .)), ends_with("2.1")) %>%
  setNames(sub("2.1", " aa", names(.)))

给出了:

#  A1 A2 A aa A2.2 A3 B1 B2 B aa B2.2 B3
#1  0  0    1    0  0  0  0    1    0  0
#2  0  0    1    0  0  0  0    1    0  0

数据

df <- structure(list(A1 = c(0L, 0L), A2 = c(0L, 0L), A2.1 = c(0L, 0L
), A2.2 = c(0L, 0L), A3 = c(0L, 0L), B1 = c(0L, 0L), B2 = c(0L, 
0L), B2.1 = c(0L, 0L), B2.2 = c(0L, 0L), B3 = c(0L, 0L)), .Names = c("A1", 
"A2", "A2.1", "A2.2", "A3", "B1", "B2", "B2.1", "B2.2", "B3"), 
class = "data.frame", row.names = c(NA, -2L))

答案 1 :(得分:2)

您可以使用grepgsub

进行尝试
x = c(0,3,5)
y = c(4,1,7)
z = c(1,2,3)
df = data.frame(x,y, z)
names(df) = c("A1","A2.1", "a2.1")

index <- grep("2.1",colnames(df))
df[, index] <- 1
colnames(df) <- gsub("2.1", "aa", colnames(df))

# > df
# A1 Aaa aaa
# 1  0   1   1
# 2  3   1   1
# 3  5   1   1

答案 2 :(得分:0)

x = c(0,3,5)
y = c(4,1,7)
df = data.frame(x,y)
names(df) = c("A1","A2.1")

df 

#A1 A2.1
#1  0    4
#2  3    1
#3  5    7

df[,(grepl("2\\.1",names(df)))] <- 0
names(df)[which(grepl("2\\.1",names(df)))] <- "aa"

print(df)

  A1 aa
1  0  0
2  3  0
3  5  0

答案 3 :(得分:0)

如果一开始只有一个字母,那么只需:

names(df)[substring(names(df),2,4) == "2.1"] <- "aa"

答案 4 :(得分:0)

以下是另一个建议:

the_two_ones <- grepl("2.1", colnames(df))
the_letters <- sapply(colnames(df)[the_two_ones], function(x) gsub("2.1", "", x))
colnames(df)[the_two_ones] <- c(paste(the_letters, "aa"))
df[,the_two_ones] <- 1 
#> df
#  A1 A2 A aa A2.2 A3 B1 B2 B aa B2.2 B3
#1  0  0    1    0  0  0  0    1    0  0
#2  0  0    1    0  0  0  0    1    0  0