英文:
setnames() in a list object in R
问题
以下是您要翻译的内容:
我有一个如下的列表对象,我需要为每个列表对象分配一个特定的名称,例如如果对象在`my.list`中的第`1`位,那么它的名称是`DF.1`,如果在第`10`位,名称是`DF.10`。非常感谢。
df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples", valueDEF = seq(0.1,0.4,0.1), valueDEF2 = seq(0.1,0.4,0.1) )
df2 <- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1), Category= "Apples2")
df3 <- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1), Category= "Apples3")
my.list <- list(df1, df2, df3);my.list
for(i in 1:length(my.list)){
my.list[[i]] <- paste("DF", i, sep = ".")
#names(my.list) <- setNames(my.list , c('list1', 'list2', 'list3')) ### in forloop
}
期望答案
names(my.list)
DF.1, DF.2, DF.3
希望这对您有所帮助。
英文:
I have a list object below and I need to assign each list object with a specific name such as if the object is in the 1st
place in my.list
, DF.1
, if it is in the 10th
place, DF.10. Many thanks in advance.
df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples", valueDEF = seq(0.1,0.4,0.1), valueDEF2 = seq(0.1,0.4,0.1) )
df2 <- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1), Category= "Apples2")
df3 <- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1), Category= "Apples3")
my.list <- list(df1, df2, df3);my.list
for(i in 1:length(my.list)){
my.list[[i]] <- paste("DF", i, sep = ".")
#names(my.list) <- setNames(my.list , c('list1', 'list2', 'list3')) ### in forloop
}
EXPECTED ANSWER
names(my.list)
DF.1, DF.2, DF.3
答案1
得分: 1
我们可以结合使用 `paste`(创建名称)和 `setNames`(将名称分配给列表):
names(my.list) <- paste0("DF.", 1:length(my.list))
names(my.list)
[1] "DF.1" "DF.2" "DF.3"
<details>
<summary>英文:</summary>
We can combine `paste` (create the names) with `setNames` (assign the names to the list):
names(my.list) <- paste0("DF.", 1:length(my.list))
names(my.list)
[1] "DF.1" "DF.2" "DF.3"
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论