What went wrong when I'm creating a new variable?

前端 未结 1 1513
故里飘歌
故里飘歌 2021-01-26 14:10

I\'d like to create a new variable based on condition imposed on the original variable. Let\'s say

  • the original variable, \"var\", is a vector consisted of a rand
1条回答
  •  盖世英雄少女心
    2021-01-26 14:59

    You can do this using either ifelse or which. With ifelse you don't need to create the column of NAs first:

    mydata$newvar <- ifelse(mydata$var < 10, mydata$var, NA)
    

    If you have already created the column of NAs, this will work:

    mydata$newvar[which(mydata$var < 10)] <- mydata$var[which(mydata$var < 10)]
    

    0 讨论(0)
提交回复
热议问题