所以我有 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
关于r - 在 R 的 for 循环中使用粘贴函数编写 ifelse 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229060/