基于R中的否定性/积极性创建标志变量

时间:2022-01-05 14:56:30

I am attempting to create a flag variable called Profit.flag that indicates whether a specific column in my dataset is profitable (>= 0) or not (<0). This is currently what I have but I am getting an error. Any help would be much obliged!

我正在尝试创建一个名为Profit.flag的标志变量,该变量指示我的数据集中的特定列是否有利可图(> = 0)或不是(<0)。这是我目前所拥有的,但我收到了一个错误。任何帮助都有很大的帮助!

Profit = data.frame(S2$Profit)
Profit.flag=numeric(474)
for(i in Profit)
  {if (Profit[i] >= 0)
  {Profit.flag[i] == 1}
  else Profit.flag[i] == 0}

2 个解决方案

#1


1  

You do not need loop here. This should work:

你这里不需要循环。这应该工作:

Profit.flag <- as.integer(S2$Profit >= 0)

or

Profit.flag <- as.integer(Profit[,1] >= 0)

#2


1  

Try this:

require(dplyr) 
df<- df %>%
         mutate(flag= ifelse(column>=0, 1, 0))

where df is your data frame and column- column name for which you want to check the value

其中df是您要检查其值的数据框和列列名称

#1


1  

You do not need loop here. This should work:

你这里不需要循环。这应该工作:

Profit.flag <- as.integer(S2$Profit >= 0)

or

Profit.flag <- as.integer(Profit[,1] >= 0)

#2


1  

Try this:

require(dplyr) 
df<- df %>%
         mutate(flag= ifelse(column>=0, 1, 0))

where df is your data frame and column- column name for which you want to check the value

其中df是您要检查其值的数据框和列列名称