Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在r中使用Inside命令定义类别_R - Fatal编程技术网

在r中使用Inside命令定义类别

在r中使用Inside命令定义类别,r,R,假设我有下表 Airbag <- read.table(header=TRUE, text= " Door Seat 1 0 1 2 2 0 3 1 0 4 0 1 5 1 0 6 1 0 7 0 0 8 0 0 9 0 2 10

假设我有下表

Airbag <- read.table(header=TRUE, text=
"      Door  Seat 
1        0      1
2        2      0      
3        1      0     
4        0      1    
5        1      0 
6        1      0
7        0      0
8        0      0
9        0      2
10       0      0")
而且

within(Airbag,{
       ab.usage[Door|Seat == 0] <- "no"
       ab.usage[Door|Seat == 1] <- "yes"
       ab.usage[Door|Seat == 2] <- "no"
       })
但也不能更改气囊$ab.usage中NA的值。

请参阅以下命令的帮助:

“in”与之类似,只是它在评估“expr”后检查环境,并对“data”的副本进行相应的修改。如果创建了无法存储在数据框中的对象,则在数据框的情况下可能会失败,并返回它“内”可用作“转换”的替代

由于返回了数据帧的修改副本,您可以将其存储在新名称下:

   Airbag.new <- within(Airbag,{
     ab.usage[Door %in% c(0, 2) | Seat %in% c(0, 2)  ] <- "no"
     ab.usage[Door == 1 | Seat == 1] <- "yes"
   })

结果很短,可以很容易地避免使用INTERIN。

如果您已经知道NA值将是什么,和/或如何获得这些值,请不要使用NA值创建新列。这只意味着更多的内存使用和复制

我建议你就这么做

Airbag$ab.usage <- with(Airbag, ifelse(Door == 1 | Seat == 1, "yes", "no"))

1.使用ifelse。2.是什么让您觉得Door | Seat==0是指定逻辑条件的正确方法两边都需要逻辑值。你是指安全气囊还是安全气囊?其中的第一个为我更改了所有NA值:Airbag$ab。用法您必须更具体一点。
   Airbag.new <- within(Airbag,{
     ab.usage[Door %in% c(0, 2) | Seat %in% c(0, 2)  ] <- "no"
     ab.usage[Door == 1 | Seat == 1] <- "yes"
   })
   Airbag.new <- within(Airbag,{
     ab.usage <- ifelse( xor(Door==1, Seat==1), "yes", "no")
   })
Airbag$ab.usage <- with(Airbag, ifelse(Door == 1 | Seat == 1, "yes", "no"))