简体   繁体   English

在R的for循环中使用粘贴函数编写ifelse语句

[英]Writing an ifelse statement with a paste function in for-loop in R

So I have 50 variables with value range from 1 to 4, and I want to count how many are 1 or 2 and how many are 3 or 4. 所以我有50个变量,值的范围是1到4,我想计算1或2的个数和3或4的个数。

ie abc1=2, abc2=2, ... abc50=3 即abc1 = 2,abc2 = 2,... abc50 = 3

and the following is my code 以下是我的代码

#Create new variable to store the counted number to

abc.low=0
abc.high=0

And here is the code I am stuck at (it doesn't work) 这是我卡住的代码(不起作用)

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))
}

I am assuming the paste function is not appropriate in what I am trying to do. 我假设粘贴功能不适用于我要执行的操作。

ie) 即)

abc1=3

abc1==3
#True

paste("abc",1,sep="")==3
# False

where the paste function should return true for my purpose. 我的粘贴功能应该返回true。

I appreciate your input! 感谢您的投入!

Try this for example: 尝试以下示例:

table(unlist(mget(paste0('abc',1:50))))
  • mget create a list of variable that unlist transform it a to a vector. mget创建一个变量列表,该列表unlist将其转换为向量。
  • table gives the occurrence of each value for example: table给出了每个值的出现,例如:

      1 2 3 4 14 13 13 10 

This will help you: 这将帮助您:

groups = rbinom(32, n = 50, prob = 0.4)
tapply(groups, groups, length)

Above tapply function returns count of elements in groups 在tapply函数上方,返回分组中元素的数量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM