有没有办法在R中将变量加在一起?

时间:2019-01-03 15:19:00

标签: r

我想将两个数字变量(strike1和boycott1)加在一起以获得一个“抗议”变量,该变量说明每种抗议类型。举个例子,这个新变量的第一个值应该是:2:3598。 我在其他变量上使用了下面的方法,它起作用了,有人知道这次不同会发生什么吗?

>table(strike
strike
           Not at all                  Once                 Twice            
             2055                  2555                   840                   
Three times .         More than three times
383                   605 
> table(boycott)
boycott
           Not at all                  Once                 Twice           
             1543                  2139                   625                   
 Three times .      More than three times
    214                    426
> strike1<-as.numeric(strike)
> boycott1<-as.numeric(boycott)
> table(strike1)
strike1
   1    2    3    4    5 
2055 2555  840  383  605 
> table(boycott1)
boycott1
   1    2    3    4    5 
1543 2139  625  214  426 
> protest<-strike1+boycott1
> table(protest)
 protest
  2   3   4   5   6   7   8   9  10 
604 284 895 179 193 124  72  38  93 
 > table(strike1, boycott1)
       boycott1
strike1   1   2   3   4   5
      1 604 154  31  10  35
      2 130 843  83  16  19
      3  21  83  98  24  13
      4   3  37  45  36  12
      5   7  36  23  26  93
  

2 个答案:

答案 0 :(得分:0)

要获得所需的输出,请尝试使用table(strike)+ table(抵制)。这将向您显示总计对每次罢工做出回应的人数,以及对抵制做出回应的人数。但是,对我来说这很难理解。

这也不会像罢工和抵制那样在个人层面上进行衡量。如果您希望使用变量来衡量抗议活动的整体参与程度,那么最好这样做

strike1 + boycott1#您的原始方法

(strike1 + boycott1)/ 2#原始变量的大小

答案 1 :(得分:0)

您正在做的是成对加法。当2strike1都等于boycott1时,您只会得到1。如果strike1[i] == 1boycott1[i] == 2,则protest[i] == 3。根据您实际要执行的操作,这实际上可能是您想要的(假设您的观察是成对的)。

要获得您期望的答案,您需要做:

protest <-  table( 2 * strike1 ) + table( 2 * boycott1 )  

但是我要避免这样做,因为(至少在我看来)这没有意义。再说一次,您的目标可能是我所缺少的。

此外,您在将strike1和boycott1一起添加的行中是否收到警告消息?像这样:

In protest<-strike1+boycott1:
  longer object length is not a multiple of shorter object length

因为我认为它应该会生成该警告。

相关问题