[英]Writing an ifelse statement with a paste function in for-loop in R
所以我有50個變量,值的范圍是1到4,我想計算1或2的個數和3或4的個數。
即abc1 = 2,abc2 = 2,... abc50 = 3
以下是我的代碼
#Create new variable to store the counted number to
abc.low=0
abc.high=0
這是我卡住的代碼(不起作用)
for (i in 1:50){
ifelse (paste("abc",i,sep="")==1|paste("abc",i,sep="")==2,
(abc.low<-abc.low<-1),(abc.low<-abc.low))
}
for (i in 1:50){
ifelse (paste("abc",i,sep="")==3|paste("abc",i,sep="")==4,
(abc.high<-abc.high<-1),(abc.high<-abc.high))
}
我假設粘貼功能不適用於我要執行的操作。
即)
abc1=3
abc1==3
#True
paste("abc",1,sep="")==3
# False
我的粘貼功能應該返回true。
感謝您的投入!
嘗試以下示例:
table(unlist(mget(paste0('abc',1:50))))
mget
創建一個變量列表,該列表unlist
將其轉換為向量。 table
給出了每個值的出現,例如:
1 2 3 4 14 13 13 10
這將幫助您:
groups = rbinom(32, n = 50, prob = 0.4)
tapply(groups, groups, length)
在tapply函數上方,返回分組中元素的數量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.