将布尔值转换为数值(0 和 1)
Convert Boolean Values to Numerical (0s & 1s)
要在 R 中编写我的模型,我需要将组名称值转换为数字 0 和 1。
这是数据框的示例:
+------------------------------------+
| state ID time amount |
+------------------------------------+
|1 open 1 0 100 |
|2 open 1 3 92 |
|3 open 2 0 101 |
|4 open 2 4 84 |
|5 closed 3 1 98 |
|6 closed 3 5 72 |
|7 closed 4 0 101 |
|8 closed 4 4 76 |
+------------------------------------+
为了能够编写我的模型,我需要将状态列转换为仅 0 表示“打开”,1 表示“关闭”。它看起来像这样:
+------------------------------------+
| state ID time amount |
+------------------------------------+
|1 0 1 0 100 |
|2 0 1 3 92 |
|3 0 2 0 101 |
|4 0 2 4 84 |
|5 1 3 1 98 |
|6 1 3 5 72 |
|7 1 4 0 101 |
|8 1 4 4 76 |
+------------------------------------+
Any suggestions on how this is done?
您可以在此处使用简单的 ifelse
语句:
df$state <- ifelse(df$state == "open", 0, 1)
这假设 state
列中出现的唯一两个值是 open
和 closed
,这可能是一个很好的假设。
另一种选择是
df$state <- +(df$state != 'open')
另一个基本 R 选项使用 match
transform(
df,
state = match(state,c("open","closed"))-1
)
要在 R 中编写我的模型,我需要将组名称值转换为数字 0 和 1。
这是数据框的示例:
+------------------------------------+
| state ID time amount |
+------------------------------------+
|1 open 1 0 100 |
|2 open 1 3 92 |
|3 open 2 0 101 |
|4 open 2 4 84 |
|5 closed 3 1 98 |
|6 closed 3 5 72 |
|7 closed 4 0 101 |
|8 closed 4 4 76 |
+------------------------------------+
为了能够编写我的模型,我需要将状态列转换为仅 0 表示“打开”,1 表示“关闭”。它看起来像这样:
+------------------------------------+
| state ID time amount |
+------------------------------------+
|1 0 1 0 100 |
|2 0 1 3 92 |
|3 0 2 0 101 |
|4 0 2 4 84 |
|5 1 3 1 98 |
|6 1 3 5 72 |
|7 1 4 0 101 |
|8 1 4 4 76 |
+------------------------------------+
Any suggestions on how this is done?
您可以在此处使用简单的 ifelse
语句:
df$state <- ifelse(df$state == "open", 0, 1)
这假设 state
列中出现的唯一两个值是 open
和 closed
,这可能是一个很好的假设。
另一种选择是
df$state <- +(df$state != 'open')
另一个基本 R 选项使用 match
transform(
df,
state = match(state,c("open","closed"))-1
)