用数字(1/0)替换逻辑值(TRUE / FALSE) [英] Replace logical values (TRUE / FALSE) with numeric (1 / 0)

查看:152
本文介绍了用数字(1/0)替换逻辑值(TRUE / FALSE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令从R中导出数据:

I am exporting data from R with the command:

write.table(output,file = "data.raw", na "-9999", sep = "\t", row.names = FALSE, col.names = FALSE)

它可以正确导出我的数据,但可以将所有逻辑变量导出为 TRUE FALSE

It exports my data correctly, but it exports all of the logical variables as TRUE and FALSE.

我需要将数据读取到只能处理数值的另一个程序中。有没有一种有效的方法在导出期间将逻辑列转换为数字1和0?我有大量的数字变量,所以我希望自动遍历data.table中的所有变量。

I need to read the data into another program that can only process numeric values. Is there an efficient way to convert logical columns to numeric 1s and 0s during the export? I have a large number of numeric variables, so I was hoping to automatically loop through all the variables in the data.table

或者,我的输出对象是 data .table 。有没有一种有效的方法可以将 data.table 中的所有逻辑变量转换为数字变量?

Alternatively, my output object is a data.table. Is there an efficient way to convert all the logical variables in a data.table into numeric variables?

如果有帮助,以下是一些代码,用于生成带有逻辑变量的 data.table (逻辑变量数量不多,但足以用于示例代码): / p>

In case it is helpful, here is some code to generate a data.table with a logical variable in it (it is not a large number of logical variables, but enough to use on example code):

DT = data.table(cbind(1:100, rnorm(100) > 0)
DT[ , V3:= V2 == 1 ]
DT[ , V4:= V2 != 1 ]


推荐答案

对于data.frame,可以使用以下命令将所有逻辑列转换为数字:

For a data.frame, you could convert all logical columns to numeric with:

# The data
set.seed(144)
dat <- data.frame(V1=1:100,V2=rnorm(100)>0)
dat$V3 <- dat$V2 == 1
head(dat)
#   V1    V2    V3
# 1  1 FALSE FALSE
# 2  2  TRUE  TRUE
# 3  3 FALSE FALSE
# 4  4 FALSE FALSE
# 5  5 FALSE FALSE
# 6  6  TRUE  TRUE

# Convert all to numeric
cols <- sapply(dat, is.logical)
dat[,cols] <- lapply(dat[,cols], as.numeric)
head(dat)
#   V1 V2 V3
# 1  1  0  0
# 2  2  1  1
# 3  3  0  0
# 4  4  0  0
# 5  5  0  0
# 6  6  1  1

使用 data.table 语法:

# Data
set.seed(144)
DT = data.table(cbind(1:100,rnorm(100)>0))
DT[,V3 := V2 == 1]
DT[,V4 := FALSE]
head(DT)
#    V1 V2    V3    V4
# 1:  1  0 FALSE FALSE
# 2:  2  1  TRUE FALSE
# 3:  3  0 FALSE FALSE
# 4:  4  0 FALSE FALSE
# 5:  5  0 FALSE FALSE
# 6:  6  1  TRUE FALSE

# Converting
(to.replace <- names(which(sapply(DT, is.logical))))
# [1] "V3" "V4"
for (var in to.replace) DT[, (var):= as.numeric(get(var))]
head(DT)
#    V1 V2 V3 V4
# 1:  1  0  0  0
# 2:  2  1  1  0
# 3:  3  0  0  0
# 4:  4  0  0  0
# 5:  5  0  0  0
# 6:  6  1  1  0

这篇关于用数字(1/0)替换逻辑值(TRUE / FALSE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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