简体   繁体   English

如何根据R中另一列中的值设置列值

[英]How to set a column value based on values in another column in R

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) (基本上如果缺少另一列或0,则将新值设置为0或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)

As long as you have tested that the column only contains 0, 1 and NA I would do: 只要您测试过该列只包含0,1和NA我会这样做:

eachfile$SalesCycleN0 <- 1
eachfile$SalesCycleN0[is.na(eachfile$R) | eachfile$R==0] <- 0

Nothing is ever "==" to NA. 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. 对于NA, grepl返回FALSE。

A more efficient way of doing this is using the sapply function, rather than using a for loop (handy in case of huge dataset). 更有效的方法是使用sapply函数,而不是使用for循环(在大型数据集的情况下很方便)。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM