创建不同的变量组合

时间:2016-01-25 06:31:29

标签: r

我有以下2个字符串 -

 mystring_ad    <- "10:20:30"
mystring_pwr    <- "010:020:030"

我想创建一个包含所有可能组合的数据框,从两个变量中取值--- 数据看起来应该像 -

10 010
10 020
10 030
20 010
20 020
20 030

我想用循环来做。任何人都可以建议如何使用r

为此编写代码

我想在数据左侧添加另一列“变量”。列中的行应该等于组合字符串的长度(答案中提到的“res”。此外,需要在所有行中复制相同的变量名。如何实现?

数据看起来应该像 -

Variable adstock power lag
Var1      10      010   0
Var1      10      020   0

等等

3 个答案:

答案 0 :(得分:3)

你甚至不需要循环。

s_ad <- strsplit(mystring_ad, ':')[[1]]
s_pwr <- strsplit(mystring_pwr, ':')[[1]]
res <- expand.grid(s_ad, s_pwr)

答案 1 :(得分:0)

我绝对会喜欢danas.zuokas解决方案。但是,仅仅因为我已经开始玩这个,你可能会有兴趣用循环来做,这里是:

mystring_ad    <- "10:20:30"
mystring_pwr    <- "010:020:030"

mystring_ad_splitted <- unlist(strsplit(mystring_ad,":"))
mystring_pwr_splitted <-unlist(strsplit(mystring_pwr,":"))


ads <- vector()
pwrs <- vector()
counter <-1

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


    ad<-mystring_ad_splitted[i];
    for (ii in 1:length(mystring_pwr_splitted)){
            pwr<-mystring_pwr_splitted[ii]
            ads[counter]<-c(ad)
            pwrs[counter]<-c(pwr)
            counter<-counter+1
    }

}

resultDF <-data.frame(ads,pwrs)

答案 2 :(得分:0)

使用循环:

mystring_ad <- "10:20:30"
mystring_pwr <- "010:020:030"

mystring <- data.frame("mystring_ad"=NA, "mystring_pwr"=NA)
mystring <- mystring[0,]
for (i in strsplit(mystring_ad, split = ":")[[1]]) {
  for (j in strsplit(mystring_pwr, split = ":")[[1]]) {
    indx <- nrow(mystring) + 1
    mystring[indx, "mystring_ad"] <- i
    mystring[indx, "mystring_pwr"] <- j
  }
}

没有循环的更简单选项:

mystring <- data.frame("mystring_ad" = rep(strsplit(mystring_ad, split = ":")[[1]], each = length(strsplit(mystring_pwr, split = ":")[[1]])), 
                           "mystring_pwr" = rep(strsplit(mystring_pwr, split = ":")[[1]], length(strsplit(mystring_ad, split = ":")[[1]])))