Generate a dummy-variable

前端 未结 17 1345
遇见更好的自我
遇见更好的自我 2020-11-21 11:41

I have trouble generating the following dummy-variables in R:

I\'m analyzing yearly time series data (time period 1948-2009). I have two questions:

  1. <
17条回答
  •  轮回少年
    2020-11-21 12:26

    The ifelse function is best for simple logic like this.

    > x <- seq(1950, 1960, 1)
    
        ifelse(x == 1957, 1, 0)
        ifelse(x <= 1957, 1, 0)
    
    >  [1] 0 0 0 0 0 0 0 1 0 0 0
    >  [1] 1 1 1 1 1 1 1 1 0 0 0
    

    Also, if you want it to return character data then you can do so.

    > x <- seq(1950, 1960, 1)
    
        ifelse(x == 1957, "foo", "bar")
        ifelse(x <= 1957, "foo", "bar")
    
    >  [1] "bar" "bar" "bar" "bar" "bar" "bar" "bar" "foo" "bar" "bar" "bar"
    >  [1] "foo" "foo" "foo" "foo" "foo" "foo" "foo" "foo" "bar" "bar" "bar"
    

    Categorical variables with nesting...

    > x <- seq(1950, 1960, 1)
    
        ifelse(x == 1957, "foo", ifelse(x == 1958, "bar","baz"))
    
    >  [1] "baz" "baz" "baz" "baz" "baz" "baz" "baz" "foo" "bar" "baz" "baz"
    

    This is the most straightforward option.

提交回复
热议问题