R语言 如何在循环中使用cbind命名列

x6h2sr28  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(205)

我使用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
soat7uwm

soat7uwm1#

一个简单的解决方案是在循环中设置 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 ...

相关问题