英文:
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 <- c(1:3)
names(v) <- letters[1:3]
What I want to do is something like this:
v <- c(1:3) %>% 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 <- 1:3 |> setNames(letters[1:3])
v
#> a b c
#> 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) <- 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 |> `names<-`(letters[1:3])
# a b c
# 1 2 3
Also, names(v) <- letters[1:3]
is equivalent to add an attribute called "names" to the vector v
, i.e.
attr(v, "names") <- letters[1:3]
Hence, the pipeline can be also written as
v |> `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) <- 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 |> `names<-`(letters[1:3])
# a b c
# 1 2 3
Also, names(v) <- letters[1:3]
is equivalent to add an attribute called "names" to the vector v
, i.e.
attr(v, "names") <- letters[1:3]
Hence, the pipeline can be also written as
v |> `attr<-`("names", letters[1:3])
# a b c
# 1 2 3
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论