How to create a new column of data in R with if statements? [duplicate]

梦想与她 提交于 2020-08-02 05:37:31

问题


I want to create a new column D of data where:

  • if column A is less than 5, then column D = column A
  • if column A is = 5, then column D = 0
  • if column A is = 6, then column D = column B

What would be the syntax?


回答1:


You don't have to use ifelse

df <- data.frame(a=1:6, 
                 b=rep("reproducible",6),
                 c=rep("example",6), stringsAsFactors=F)
df$d <- df$a
df$d[df$a==5] <- 0
df$d[df$a==6] <- df$b[df$a==6]
df
# > df
#   a            b       c            d
# 1 1 reproducible example            1
# 2 2 reproducible example            2
# 3 3 reproducible example            3
# 4 4 reproducible example            4
# 5 5 reproducible example            0
# 6 6 reproducible example reproducible

But you could if you really want to.

within(df, df$d <- ifelse(a<5, a, 
                        ifelse(a==5, 0,
                               ifelse(a==6,b,NA))) ) #same result



回答2:


If you mean the sum of A is greater than 5. Then you can just make a vector for D then make it into a column using rbind()

d <- c()
if(sum(A)<5){
d = A
}else if(sum(A) ==5){
d = 0
}else if(sum(A) == 6){
d = B
}
D <- rbind(d)

I actually don't know if this will work because you haven't covered all your cases, and I don't know exactly what you mean by a column "equalling" 5.



来源:https://stackoverflow.com/questions/31150764/how-to-create-a-new-column-of-data-in-r-with-if-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!