Generate a dummy-variable

前端 未结 17 1364
遇见更好的自我
遇见更好的自我 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:12

    The simplest way to produce these dummy variables is something like the following:

    > print(year)
    [1] 1956 1957 1957 1958 1958 1959
    > dummy <- as.numeric(year == 1957)
    > print(dummy)
    [1] 0 1 1 0 0 0
    > dummy2 <- as.numeric(year >= 1957)
    > print(dummy2)
    [1] 0 1 1 1 1 1
    

    More generally, you can use ifelse to choose between two values depending on a condition. So if instead of a 0-1 dummy variable, for some reason you wanted to use, say, 4 and 7, you could use ifelse(year == 1957, 4, 7).

提交回复
热议问题