我想在循环中为变量'ax'赋值。我的代码是:
ax<-0
for (i in i:4){
if(i%%4==1)
{
ax[i]<-"one"
}
else if(i%%4==2)
{
ax[i]<-"two"
}
else if(i%%4==3)
{
ax[i]<-"three"
}
else
{
ax[i]<-"four"
}
}
我希望我有斧头[1],斧头[2],斧头[3]和斧头[4],
"one" "two" "three" "four"
但我得到了:
"0" NA NA "four"
这只是一次尝试,真正的代码要长得多。但是主要的问题是关于为各个数组变量赋值。这有什么不对吗?
这里我添加了真实的代码
#library(sqldf)
n = 4
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
Sui_Q1_STS<-0
Sui_Q1_TS<-0
Sui_Q1_S<-0
Sui_Q1_SS<-0
Sui_Q2_STS<-0
Sui_Q2_TS<-0
Sui_Q2_S<-0
Sui_Q2_SS<-0
for (i in 1:n){
if(i%%4==1)
{
a<-sqldf("SELECT count([X.0]) from testes where [X.0]='Sangat Tidak Setuju' and (StartDate like '%11/05/2015 00:%' or StartDate like '%11/05/2015 01:%' or StartDate like '%11/05/2015 02:%' or StartDate like '%11/05/2015 03:%' or StartDate like '%11/05/2015 04:%' or StartDate like '%11/05/2015 05:%' or StartDate like '%11/05/2015 06:00%')")
#b c d e f g and h are also sqldf
Sui_Q1_STS[i]<-as.numeric(a)
Sui_Q1_TS[i]<-as.numeric(b)
Sui_Q1_S[i]<-as.numeric(c)
Sui_Q1_SS[i]<-as.numeric(d)
Sui_Q2_STS[i]<-as.numeric(e)
Sui_Q2_TS[i]<-as.numeric(f)
Sui_Q2_S[i]<-as.numeric(g)
Sui_Q2_SS[i]<-as.numeric(h)
Sui_Q1<-list()
Sui_Q1[[i]]<-cbind(Sui_Q1_STS[i],Sui_Q1_TS[i],Sui_Q1_S[i],Sui_Q1_SS[i])
Sui_Q2<-list()
Sui_Q2[[i]]<-cbind(Sui_Q2_STS[i],Sui_Q2_TS[i],Sui_Q2_S[i],Sui_Q2_SS[i])
Total[i]<-Sui_Q1[[i]][,1]+Sui_Q1[[i]][,2]+Sui_Q1[[i]][,3]+Sui_Q1[[i]][,4]
}
else if(i%%4==2){
#only different in SQL
}
else if(i%%4==3){
#only different in SQL
}
else if(i%%4==0){
#only different in SQL
}
}
我得到了:
> Sui_Q1
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
[,1] [,2] [,3] [,4]
[1,] 0 0 4 4
答案 0 :(得分:3)
如果我们需要将数字转换为英文单词
library(english)
english(v1)
#[1] two one three three three four two four four two
或使用base R
没有任何循环
c("four", "one", "two", "three")[as.numeric(factor((v1%%4==1) +
2*(v1%%4==2) + 4*(v1%%4==3)))]
#[1] "two" "one" "three" "three" "three" "four" "two" "four" "four" "two"
如果我们真的需要一个循环
ax <- numeric(4)
for(i in 1:4){
if(i%%4 ==1){
ax[i] <- "one"
} else if (i%%4 ==2){
ax[i] <- "two"
}else if (i%%4 ==3){
ax[i] <- "three"
} else {
ax[i] <- "four"
}
}
ax
#[1] "one" "two" "three" "four"
set.seed(24)
v1 <- sample(1:4, 10, replace=TRUE)
答案 1 :(得分:2)
这个非常简单的表达式可以满足您的需求:
i <- 1:4
c("four", "one", "two", "three")[i %% 4 + 1]
## [1] "one" "two" "three" "four"