在R中的列表对象中的setnames()函数。

huangapple go评论66阅读模式
英文:

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 &lt;- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= &quot;Apples&quot;, valueDEF = seq(0.1,0.4,0.1), valueDEF2 = seq(0.1,0.4,0.1) )
    df2 &lt;- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1),  Category= &quot;Apples2&quot;)
    df3 &lt;- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1),  Category= &quot;Apples3&quot;)
    
    my.list  &lt;- list(df1, df2, df3);my.list 
    
    for(i in 1:length(my.list)){
      my.list[[i]] &lt;-  paste(&quot;DF&quot;, i, sep = &quot;.&quot;)
      #names(my.list) &lt;- setNames(my.list , c(&#39;list1&#39;, &#39;list2&#39;, &#39;list3&#39;)) ### 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>



huangapple
  • 本文由 发表于 2023年5月8日 00:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定