简体   繁体   English

用名称创建r向量

[英]create r vector with names

I have this output that I can create with static inputs: 我可以使用静态输入创建以下输出:

t1 = c("dog"="dog","cat"= "cat")
t1

Results:
     dog   cat 
    "dog" "cat" 

How can I create those same results with only the t$animal character vector below 我如何只用下面的t $动物字符向量创建相同的结果

t = data.frame(animal = c("dog","cat"))
c(t$animal =t$animal)  # this does not work

Convert to character and then use names<- (or setNames ): 转换为字符,然后使用names<- (或setNames ):

ch <- as.character(unlist(t))
names(ch) <- ch
ch
##   dog   cat 
## "dog" "cat" 

You can use setNames 您可以使用setNames

t2 <- setNames(t$animal, t$animal)
t2

#dog cat 
#dog cat 

data 数据

t <- data.frame(animal = c("dog","cat"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM