gpt4 book ai didi

R:使用 get() 和 paste() 返回列

转载 作者:行者123 更新时间:2023-12-02 00:56:48 25 4
gpt4 key购买 nike

为什么 get()paste() 的组合适用于数据帧,但不适用于数据帧中的列?我怎样才能让它发挥作用?

ab<-12
get(paste("a","b",sep=""))
# gives: [1] 12

ab<-data.frame(a=1:3,b=3:5)
ab$a
#gives: [1] 1 2 3

get(paste("a","b",sep=""))
# gives the whole dataframe

get(paste("ab$","a",sep=""))
# gives: Error in get(paste("ab$", "a", sep = "")) : object 'ab$a' not found

最佳答案

数据框中的列不是一流的对象。它们的“名称”实际上是列表提取的索引值。尽管 names 函数的存在造成了可以理解的混淆,但它们并不是真正的 R 名称,即 R 对象列表中未加引号的标记或符号。请参阅 ?is.symbol 帮助页面。 get 函数获取一个字符值,然后在工作区中查找它并返回它以供进一步处理。

> ab<-data.frame(a=1:3,b=3:5)
> ab$a
[1] 1 2 3
> get(paste("a","b",sep=""))
a b
1 1 3
2 2 4
3 3 5
>
> # and this would be the way to get the 'a' column of the ab object

get(paste("ab",sep=""))[['a']]

如果有一个命名对象 target 的值为 "a"tehn 你也可以这样做:

target <- "a"
get(paste("ab",sep=""))[[target]] # notice no quotes around target
# because `target` is a _real_ R name

关于R:使用 get() 和 paste() 返回列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com