How to set a column value based on values in anoth

2019-07-19 07:57发布

I am trying to add a new column based on values in another column. (Basically if the other column is missing or 0, set the new value to 0 or to 1)

What's wrong with this code below?

times=nrow(eachfile)
for(i in 1:times)
{eachfile$SalesCycleN0[i] <- ifelse(eachfile$R[i]==NA | eachfile$R[i]==0,0,1 ) }

table(eachfile$SalesCycleN0)

标签: r
3条回答
Bombasti
2楼-- · 2019-07-19 08:38

As long as you have tested that the column only contains 0, 1 and NA I would do:

eachfile$SalesCycleN0 <- 1
eachfile$SalesCycleN0[is.na(eachfile$R) | eachfile$R==0] <- 0
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-19 08:41

A more efficient way of doing this is using the sapply function, rather than using a for loop (handy in case of huge dataset). Here is an example:

 df = data.frame(x = c(1,2,0,NA,5))

 fun = function(i) {is.na(df$x[i]) || (df$x[i] == 0)}
 bin <- (sapply(1:nrow(df), FUN = fun))*1  ## multiplying by 1 will convert the logical vector to a binary one.
 df <- cbind(df, bin)

In your case:

 fun = function(i) {is.na(eachfile$SalesCycleNO[i]) || (eachfile$SalesCycleNO[i] == 0)}
 bin <- (sapply(1:times, FUN = fun))*1
 eachfile <- cbind(eachfile, bin)
查看更多
虎瘦雄心在
4楼-- · 2019-07-19 09:01

Nothing is ever "==" to NA. Just do this (no loop):

eachfile$SalesCycleN0 <- ifelse( is.na(eachfile$R) | eachfile$R==0, 0,1 ) 

If you were looking for a little more economy in code this might also work:

eachfile$SalesCycleN0 <- as.numeric( !grepl("^0$", eachfile$R) )

grepl returns FALSE for NA's.

查看更多
登录 后发表回答