R操作特定序列的字符向量 [英] R manipulation a character vector for a specific sequence

查看:46
本文介绍了R操作特定序列的字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个商品ID列表,如下所示:

I have a list of item ids as below:

ids <- c("12_a","23_b")

考虑到这些项目ID,我想为以下三个组(G1,G2和G3)生成一个字符变量.

Considering these item ids, I would like to generate a character variable as below for three groups (G1, G2, and G3).

    #for the first item
Equal = (G1,12_a, Slope[0]), 
        (G2,12_a, Slope[0]), 
        (G3,12_a, Slope[0]);
Equal = (G1,12_a, Slope[1]), 
        (G2,12_a, Slope[1]), 
        (G3,12_a, Slope[1]);
Equal = (G1,12_a, Slope[2]), 
        (G2,12_a, Slope[2]), 
        (G3,12_a, Slope[2]);
Equal = (G1,12_a, Intercept[0]), 
        (G2,12_a, Intercept[0]), 
        (G3,12_a, Intercept[0]);
    
    #for the second item
Equal = (G1,23_b, Slope[0]), 
        (G2,23_b, Slope[0]), 
        (G3,23_b, Slope[0]);
Equal = (G1,23_b, Slope[1]), 
        (G2,23_b, Slope[1]), 
        (G3,23_b, Slope[1]);
Equal = (G1,23_b, Slope[2]), 
        (G2,23_b, Slope[2]), 
        (G3,23_b, Slope[2]);
Equal = (G1,23_b, Intercept[0]), 
        (G2,23_b, Intercept[0]), 
        (G3,23_b, Intercept[0]);

所需输出的逻辑是对于三个组, Slope [] 中的值应为 0,1,和3 .和 Intercept [] 的值应为三个组的 0 三次.

The logic behind the desired output is the values in Slope[] should be 0,1, and 3 for three groups. and Intercept[] values should be 0 for three times for three groups.

有人之前有类似的东西吗?

Did anyone have anything similar before?

谢谢!

推荐答案

这就是我所想的.

ids <- c("12_a","23_b")
group <- 3
Slope.0 <- c() # store slope vector
Intercept.0 <- c() # store intercept vector

for(i in 1:length(ids)) {

  for(j in 0:group) { # here with the length(State) I gained the sequqnece of 0,1,2,3
    slope.0 <- paste0(paste0("Equal = ",paste0(paste("(", "G1, ",ids[i], ","," Slope[",j,"])",collapse=", ", sep=""),", ",
                                        paste( "(", "G2, ",ids[i], ","," Slope[",j,"])",collapse=", ", sep=""),", ",
                                        paste( "(", "G3, ",ids[i], ","," Slope[",j,"])",collapse=", ", sep=""))), ";")
    Slope.0 <- c(Slope.0, slope.0)
    
  }
  
  
  
  intercept.0 <- paste0(paste0("Equal = ",paste0(paste("(", "G1, ",ids[i], ","," Intercept[0])",collapse=", ", sep=""),", ",
                                          paste( "(", "G2, ",ids[i], ","," Intercept[0])",collapse=", ", sep=""),", ",
                                          paste( "(", "G3, ",ids[i], ","," Intercept[0])",collapse=", ", sep=""))),";")
  Intercept.0 <- c(Intercept.0, intercept.0)}

这篇关于R操作特定序列的字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆