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

前端 未结 1 843
野性不改
野性不改 2021-01-26 14:23

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:49

    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)
提交回复
热议问题