I am exporting data from R with the command:
write.table(output,file="data.raw", na "-9999",sep="\t",row.names=F,col.names=F)
that exports my data correctly, but it exports all of the logical variables as TRUE and FALSE.
I need to read the data into another program that can only process numeric values. Is there an efficient way to convert these 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
I realize I could run simple sed script on the output data, but it seems like this should be straight forward to do from R.
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?
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 ]
This seems like an easy question, but its throwing me off, so thank you for the help!
As Ted Harding pointed out in the R-help mailing list, one easy way to convert logical objects to numeric is to perform an arithmetic operation on them. Convenient ones would be
* 1
and+ 0
, which will keep the TRUE/FALSE == 1/0 paradigm.For your mock data (I've changed the code a bit to use regular R packages and to reduce size):
The dataset you get has a mixture of numeric and boolean variables:
Now let
(If your dataset contains character or factor variables, you will need to apply this operation to a subset of
df
filtering out those variables)df2
is equal toWhich is 100% numeric, as
str(df2)
will show you.Now you can safely export
df2
to your other program.What about just a:
or another approach could be with
dplyr
in order to retain the previous column if the case (no one knows) your data will be imported in R.Edit: Loop
I do not know if my code here is performing but it checks all column and change to numerical only those that are logical. Of course if your
TRUE
andFALSE
are not logical but character strings (which might be remotely) my code won't work.Simplest way of doing this!
Multiply your matrix by 1
For example:
# [,1] [,2] [,3] [,4]
# [1,] TRUE TRUE TRUE FALSE
# [2,] FALSE TRUE FALSE TRUE
# [,1] [,2] [,3] [,4]
# [1,] 1 1 1 0
# [2,] 0 1 0 1
(You could also add zero:
B <- 0+A
)If there are multiple columns, you could use
set
(using @josilber's example)For a data.frame, you could convert all logical columns to numeric with:
In
data.table
syntax: