R 创建不同的变量组合
我有以下两个字符串-R 创建不同的变量组合,r,R,我有以下两个字符串- mystring_ad <- "10:20:30" mystring_pwr <- "010:020:030" 我想用循环来做。有人能建议如何使用r编写此代码吗 我想从数据的左边添加另一个列变量。列中的行数应该等于答案中提到的组合stringres的长度。此外,需要在所有行中复制相同的变量名。如何做到这一点 数据应该是- 10 010 10 020 10 030 20 010 20 020 20 030 Variable adstock pow
mystring_ad <- "10:20:30"
mystring_pwr <- "010:020:030"
我想用循环来做。有人能建议如何使用r编写此代码吗
我想从数据的左边添加另一个列变量。列中的行数应该等于答案中提到的组合stringres的长度。此外,需要在所有行中复制相同的变量名。如何做到这一点
数据应该是-
10 010
10 020
10 030
20 010
20 020
20 030
Variable adstock power lag
Var1 10 010 0
Var1 10 020 0
因此,您甚至不需要循环
s_ad <- strsplit(mystring_ad, ':')[[1]]
s_pwr <- strsplit(mystring_pwr, ':')[[1]]
res <- expand.grid(s_ad, s_pwr)
我肯定更喜欢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)
使用循环:
无回路的更简单选项:
谢谢!!这确实是一个很大的帮助
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]])))