简体   繁体   English

R-创建包含数字范围的名称的向量

[英]R - create vector of names containing range of numbers

I have a list of variable names {'X14_question_1', 'X14_question_2' ... etc }, let's say there are 20 of them. 我有一个变量名列表{'X14_question_1','X14_question_2'...等等},假设有20个。 How do I assign those names to a vector without needing to type in all of them by hand? 如何将这些名称分配给矢量而无需手动输入所有名称?

Can I do it somehow similarly to this - vector = c('X14_question_'1':20) (this exact syntax isn't working obv), or do I must use the loop? 我能以某种方式做到这一点vector = c('X14_question_'1':20) (此确切的语法无法正常工作),还是必须使用循环?

Turns out it was relatively easy to find an answer, I just wasn't looking in the right place! 事实证明,找到答案相对容易,我只是没有在正确的位置寻找!

Thanks anyway. 不管怎么说,还是要谢谢你。 :) :)

vector=c(paste("X14_question_",1:20,sep=""))

I like sprintf for these types of things since it also allows you to do some transformation in the process. 我喜欢sprintf来处理这些类型的事情,因为它还允许您在过程中进行一些转换。

Here's a basic (no transformation) approach: 这是一种基本的方法(无需转换):

vec1 <- sprintf('X14_question_%d', 1:20)
head(vec1)
# [1] "X14_question_1" "X14_question_2" "X14_question_3" "X14_question_4"
# [5] "X14_question_5" "X14_question_6"

Here's an approach that pads zeroes in the number to make sorting easier. 这是在数字中填充零以简化排序的方法。

vec2 <- sprintf('X14_question_%02d', 1:20)
head(vec2)
# [1] "X14_question_01" "X14_question_02" "X14_question_03" "X14_question_04"
# [5] "X14_question_05" "X14_question_06"

Let's see if this helps you: 让我们看看这是否对您有帮助:

vars <- paste('X14_question_', 1:20)
v <- vector()
for(i in 1:length(vars)) {
  v[i] <- eval(parse(text = vars[i]))
}

Maybe this is not the cleanest way, but it may work 也许这不是最干净的方法,但可能有效

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

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