以下数据框:
df <- data.frame(matrix(rnorm(9*9), ncol=9))
names(df) <- c("c_1", "d_1", "e_1", "a_p", "b_p", "c_p", "1_o1", "2_o1", "3_o1")
row.names(df) <- names(df)
...根据在“_”之后找到的常见索引按rownames分割,我将数据帧从列表发布到全局环境:
list_all <- split(df,sub(".+_","",rownames(df)))
list2env(list_all,envir=.GlobalEnv)
我的许多数据框现在都有数字名称,并且无法轻易解决,因此我想更改其名称。我想在每个名字上添加“df_”,但由于我不知道怎么做,我被告知make.names可能会很好。我创建了一个包含所有唯一索引的向量,并对其进行分解,我认为它保持了索引的原始顺序:
indx <- gsub(".*_", "", names(df))
indx1 <- factor(indx, levels=unique(indx))
new.names <- make.names(unique(indx1))
new.names
[1] "X1" "p" "o1"
new.names按我想要的顺序排列。我将新名称应用于列表,并将其发布到环境中 list_all&lt; - setNames(list_all,new.names) list2env(list_all,ENVIR = .GlobalEnv)
现在,数字名称添加了前导X(很好!),但数据帧的序列已更改,名称分配错误(dataframe p现在包含所有带“o1”的行,反之亦然)。
谢谢!
答案 0 :(得分:2)
为什么不在创建list_all
后简单地使用:
names(list_all) = paste0("df_", names(list_all))
list2env(list_all,envir=.GlobalEnv)
#> df_1
# c_1 d_1 e_1 a_p b_p c_p 1_o1 2_o1 3_o1
#c_1 1.10388982 -0.2329471 -0.3330288 -2.0477186 -1.4576052 1.5411154 -0.9529714 0.289516457 -0.01017546
#d_1 -1.02420662 -0.1002591 -0.7884373 1.5021531 0.3551084 0.7755127 0.7679464 -0.002950944 -0.69849456
#e_1 -0.02004774 -0.1873947 -0.3674220 0.7321503 0.9076226 -0.4997974 -0.2915408 -1.376529597 -1.43563284
答案 1 :(得分:1)
这是我认为你想要的功能:
# dummy data:
x <- numeric(0)
y <- numeric(0)
z <- numeric(0)
df1 <- data.frame()
df2 <- data.frame()
df3 <- data.frame()
df4 <- data.frame()
renameObjects <- function(env=.GlobalEnv, class, pfx) {
objs <- ls(envir = env) # get list of objects
classes <- sapply(objs, function(x) class(get(x))) == class
for (obj in objs[classes]) {
assign(paste0(pfx, obj), get(obj), envir = env)
}
rm(list=objs[classes], envir = env)
}
# run the function
renameObjects(class='data.frame', pfx = 'my_prefix_')
结果
> ls()
[1] "df1" "df2" "df3" "df4"
[5] "renameObjects" "x" "y" "z"
> renameObjects(class='data.frame', pfx = 'my_prefix_')
> ls()
[1] "my_prefix_df1" "my_prefix_df2" "my_prefix_df3" "my_prefix_df4"
[5] "renameObjects" "x" "y" "z"