重命名管道中的字符向量

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

Rename character vector in pipeline

问题

我能将以下两段代码连接成一个管道吗?

v <- c(1:3)
names(v) <- letters[1:3]

我想要做的是像这样:

v <- c(1:3) %>% rename_with(~ letters[1:3])

当然它不起作用,它会显示:

"Error in UseMethod("rename_with") : no applicable method for 'rename_with' applied to an object of class 'c('integer', 'numeric')"

我想这么做的原因是我需要使用targets包构建类似上面的v对象。

英文:

Can I connect the following two codes into one with the pipeline?

v &lt;- c(1:3)
names(v) &lt;- letters[1:3]

What I want to do is something like this:

v &lt;- c(1:3) %&gt;% rename_with(~ letters[1:3])

Of course it doesn't work; it says:
>"Error in UseMethod("rename_with") : no applicable method for 'rename_with' applied to an object of class "c('integer', 'numeric')"

The reason I want to do this is that I need to construct an object like v above using the targets package.

答案1

得分: 5

只需使用 setNames() 进行操作:

v <- 1:3 |> setNames(letters[1:3])
v
#> a b c 
#> 1 2 3

创建于2023年07月11日,使用 reprex v2.0.2

英文:

Just do it with setNames():

v &lt;- 1:3 |&gt; setNames(letters[1:3])
v
#&gt; a b c 
#&gt; 1 2 3

<sup>Created on 2023-07-11 with reprex v2.0.2</sup>

答案2

得分: 1

I prefer using setNames() like @LiangZhang's answer. Here I provide another point of view for this issue.


This line names(v) &lt;- letters[1:3] is actually evaluated as follows:

`names<-`(v, letters[1:3])

You can regard `names<-` as a function and adapt it for a pipeline:

v |&gt; `names<-`(letters[1:3])

# a b c 
# 1 2 3

Also, names(v) &lt;- letters[1:3] is equivalent to add an attribute called "names" to the vector v, i.e.

attr(v, "names") &lt;- letters[1:3]

Hence, the pipeline can be also written as

v |&gt; `attr<-`("names", letters[1:3])

# a b c 
# 1 2 3
英文:

I prefer using setNames() like @LiangZhang's answer. Here I provide another point of view for this issue.


This line names(v) &lt;- letters[1:3] is actually evaluated as follows:

`names&lt;-`(v, letters[1:3])

You can regard `names&lt;-` as a function and adapt it for a pipeline:

v |&gt; `names&lt;-`(letters[1:3])

# a b c 
# 1 2 3

Also, names(v) &lt;- letters[1:3] is equivalent to add an attribute called "names" to the vector v, i.e.

attr(v, &quot;names&quot;) &lt;- letters[1:3]

Hence, the pipeline can be also written as

v |&gt; `attr&lt;-`(&quot;names&quot;, letters[1:3])

# a b c 
# 1 2 3

huangapple
  • 本文由 发表于 2023年7月11日 15:06:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76659436.html
匿名

发表评论

匿名网友

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

确定