我需要重命名数据框列表中的一列。新的列名称需要反映它所属的数据框的名称。例如,我想将“字母”列分别重命名为“ 1”和“ 2”(Letters_1和Letters_2),或者类似的方法也可以。
这是一个可重复的例子
#Create a list containing dataframes
datasets=list()
Numbers <- c(1,2,3,4)
Letters <- c("A","B","C","D")
DF1 <- data.frame(Numbers, Letters)
Numbers <- c(1,9,3,14)
Letters <- c("A","Z","C","X")
DF2 <- data.frame(Numbers, Letters)
datasets[[1]] <- DF1
datasets[[2]] <- DF2
head(datasets[])
此示例生成以下数据结构
[[1]]
Numbers Letters
1 1 A
2 2 B
3 3 C
4 4 D
[[2]]
Numbers Letters
1 1 A
2 9 Z
3 3 C
4 14 X
我想要的输出低于
[[1]]
Numbers 1
1 1 A
2 2 B
3 3 C
4 4 D
[[2]]
Numbers 2
1 1 A
2 9 Z
3 3 C
4 14 X
这是我尝试使用for循环的方法。
# Rename column using for loop
list <- c(1,2)
for (name in list){
colnames(datasets[[print(paste(`name`, sep=""))]][2]) <- c(print(paste(`name`, sep="")))
}
答案 0 :(得分:3)
我们可以遍历每个列表元素,并使用setNames
datasets[] <- lapply(seq_along(datasets), function(x)
setNames(datasets[[x]],
replace(names(datasets[[x]]), names(datasets[[x]]) == "Letters", x)))
datasets
#[[1]]
# Numbers 1
#1 1 A
#2 2 B
#3 3 C
#4 4 D
#[[2]]
# Numbers 2
#1 1 A
#2 9 Z
#3 3 C
#4 14 X
答案 1 :(得分:1)
您只需稍作修改就可以使用for循环解决方案。
for(x in seq_along(datasets))
names(datasets[[x]])[names(datasets[[x]]) == 'Letters'] <- x
datasets
# [[1]]
# Numbers 1
# 1 1 A
# 2 2 B
# 3 3 C
# 4 4 D
#
# [[2]]
# Numbers 2
# 1 1 A
# 2 9 Z
# 3 3 C
# 4 14 X
答案 2 :(得分:1)
如果您为列表命名,并且只想在Letters
列中添加data.frame名称,那么它将起作用:
> Numbers <- c(1,2,3,4)
> Letters <- c("A","B","C","D")
> DF1 <- data.frame(Numbers, Letters)
> Numbers <- c(1,9,3,14)
> Letters <- c("A","Z","C","X")
> DF2 <- data.frame(Numbers, Letters)
>
> datasets <- list(
+ DF1 = DF1,
+ DF2 = DF2
+ )
>
> datasets <- sapply(names(datasets), function(x) {
+ df <- datasets[[x]]
+ i <- which(colnames(df) == "Letters")
+ colnames(df)[i] <- paste0("Letters_", x)
+ df
+ }, simplify = FALSE)
>
> datasets
$DF1
Numbers Letters_DF1
1 1 A
2 2 B
3 3 C
4 4 D
$DF2
Numbers Letters_DF2
1 1 A
2 9 Z
3 3 C
4 14 X
答案 3 :(得分:0)
您可以为数据集元素定义名称,然后在循环中访问它们:
names(datasets) <- c("DF1","DF2")
for (i in 1:length(datasets))
{
print(names(datasets)[i])
}
[1] "DF1"
[1] "DF2"