数据表中的条件语句 [英] conditional statements in data.table

查看:74
本文介绍了数据表中的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用条件语句来获取数据表中的一些变量。以下是一些简化数据,代码和结果:

I am trying to use conditional statements to obtain some variables in a data table. Here's some simplified data, the code and the results:

> dt
   id trial  bet outcome
1: 11     1    1       6
2: 11     2  456       2
3: 11     3 3456       3
4: 11     4  456       6
5: 12     1   34       6
6: 12     2 3456       2
7: 12     3   12       4
8: 12     4  123       2

dt1=dt[,list(
nbet=nchar(bet),
if (nchar(bet)>2.5) riskybet=1 else riskybet=0,
if (grepl(outcome,bet)==TRUE) win=1 else win=0),
by='id,trial']

> dt1
   id trial nbet V2 V3
1: 11     1    1  0  0
2: 11     2    3  1  0
3: 11     3    4  1  1
4: 11     4    3  1  1
5: 12     1    2  0  0
6: 12     2    4  1  0
7: 12     3    2  0  0
8: 12     4    3  1  1

条件语句按原样工作,但没有赋予变量名'riskybet'和'win'它们显示为V2和V3。

The conditional statements are working as they should but without the assigned variable names 'riskybet' and 'win', i.e. they appear as V2 and V3. What am I doing wrong?

推荐答案

您正在为if / else语句中的变量赋值。尝试以下操作:

You are assigning values to variables "inside" the if/else-statement. Try this:

dt1=dt[,list(
 nbet=nchar(bet),
 riskybet = if (nchar(bet)>2.5) 1 else 0,
 win = if (grepl(outcome, bet)) 1 else 0),
    by='id,trial']

   id trial nbet riskybet win
1: 11     1    1        0   0
2: 11     2    3        1   0
3: 11     3    4        1   1
4: 11     4    3        1   1
5: 12     1    2        0   0
6: 12     2    4        1   0
7: 12     3    2        0   0
8: 12     4    3        1   1

或者,您也可以使用 ifelse if-else

Alternatively you could also use ifelse instead of the traditional if-else.

这篇关于数据表中的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆