我试图在循环函数中使用年份和月份的字符串的特定格式,但是我想在字符串的月份中访问特定的变量。知道变量具有该月的数字:例如cycle1指的是2013-01的周期。
months <- c("2013-01", "2013-02", "2013-03")
cycle1 <- 0
cycle2 <- 0
cycle3 <- 0
for (k in months)
{
print(k) # I need to use this "YYYY-mm" format
#print(cycle1) # But what I also need to print is : Cycle1 Cycle2 Cycle3 Cycle4 etc.
}
我知道可以通过使用assign()函数来实现,但是我还没有弄清楚如何在将例如2013-06转换为6的函数中使用它。 谢谢!
编辑:作为输出,我要打印:具有循环功能的“ 2013-01” cycle1“ 2013-02” cycle2“ 2013-03” cycle3。
答案 0 :(得分:0)
我不确定您是否要使用cycle1,cycle2等的名称或值。以下是两个可能的答案:
library(stringr)
months <- c("2013-01", "2013-02", "2013-03")
cycle1 <- 0
cycle2 <- 0
cycle3 <- 0
cycle <- list(cycle1, cycle2, cycle3)
for (i in 1:length(months)) {
print(months[i])
print(cycle[[as.numeric(str_sub(months[i], 6, 7))]])
}
给出以下结果:
[1] "2013-01"
[1] 0
[1] "2013-02"
[1] 0
[1] "2013-03"
[1] 0
还有这个
library(stringr)
months <- c("2013-01", "2013-02", "2013-03")
cycle1 <- 0
cycle2 <- 0
cycle3 <- 0
cycle <- list(cycle1 = cycle1, cycle2 = cycle2, cycle3 = cycle3)
for (i in 1:length(months)) {
print(months[i])
print(names(cycle[as.numeric(str_sub(months[i], 6, 7))]))
}
哪个给出这个结果
[1] "2013-01"
[1] "cycle1"
[1] "2013-02"
[1] "cycle2"
[1] "2013-03"
[1] "cycle3"
答案 1 :(得分:0)
months <- c("2013-01", "2013-02", "2013-03")
lapply(1:length(months), function(x) assign(paste0("cycle", x), months[[x]], envir = globalenv()))
我想这就是你想要的吗?