我正在使用循环使用cbind重命名列。每次我尝试使用循环索引(i)命名列时,它都不使用索引,而是将i作为列名。我希望它显示原始
的实际名称x <- seq(0, 50, by = 1)
y <- seq(50, 100, by = 1)
z <- seq(25, 75, by = 1)
df <- data.frame(cbind(x, y, z))
df_final <- NULL
for (i in colnames(df)){
#PROBLEM: Column names becomes i instead of the actual column names
df_final <- cbind(df_final, i = df[,i])
}
df_final
答案 0 :(得分:0)
我想我理解了您的问题,但是,对于要使用代码实现什么我感到很困惑。
如果您只想重命名colnames
,则无需使用循环:
names_list <- list("New Name Col1", "New Name Col2", "New Name Col3")
names(df) <- names_list
如果您对循环解决方案的外观感兴趣:
for(i in 1:length(names_list)){
names(df)[i] <- names_list[[i]]
}
数据:
df <- data.frame(x = seq(0, 50, by = 1), y = seq(50, 100, by = 1), z = seq(25, 75, by = 1))
答案 1 :(得分:0)
一个简单的解决方案是在循环中设置 colname ,例如:
df_final <- NULL
for (i in colnames(df)){
df_final <- cbind(df_final, df[,i])
colnames(df_final)[ncol(df_final)] <- i
}
colnames(df_final)
#[1] "x" "y" "z"
str(df_final)
# num [1:51, 1:3] 0 1 2 3 4 5 6 7 8 9 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:3] "x" "y" "z"
要使用方法x[[i]] <- value
,x需要具有行:
df_final <- data.frame()[seq_len(nrow(df)),0] #Create empty data frame with rows
for (i in colnames(df)){
df_final[[i]] <- df[,i]
}
colnames(df_final)
#[1] "x" "y" "z"
str(df_final)
#'data.frame': 51 obs. of 3 variables:
# $ x: num 0 1 2 3 4 5 6 7 8 9 ...
# $ y: num 50 51 52 53 54 55 56 57 58 59 ...
# $ z: num 25 26 27 28 29 30 31 32 33 34 ...
否则它将创建一个列表:
df_final <- NULL
for (i in colnames(df)){
df_final[[i]] <- df[,i]
}
colnames(df_final)
#NULL
str(df_final)
#List of 3
# $ x: num [1:51] 0 1 2 3 4 5 6 7 8 9 ...
# $ y: num [1:51] 50 51 52 53 54 55 56 57 58 59 ...
# $ z: num [1:51] 25 26 27 28 29 30 31 32 33 34 ...
df_final <- do.call("cbind", df_final)
colnames(df_final)
#[1] "x" "y" "z"
str(df_final)
# num [1:51, 1:3] 0 1 2 3 4 5 6 7 8 9 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:3] "x" "y" "z"
使用sapply
而非for
完成循环时,解决方案是:
df_final <- sapply(colnames(df), function(i) {df[,i]})
colnames(df_final)
#[1] "x" "y" "z"
str(df_final)
# num [1:51, 1:3] 0 1 2 3 4 5 6 7 8 9 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:3] "x" "y" "z"
或者只是子集:
df_final <- df[colnames(df)]
colnames(df_final)
#[1] "x" "y" "z"
str(df_final)
#'data.frame': 51 obs. of 3 variables:
# $ x: num 0 1 2 3 4 5 6 7 8 9 ...
# $ y: num 50 51 52 53 54 55 56 57 58 59 ...
# $ z: num 25 26 27 28 29 30 31 32 33 34 ...