简体   繁体   中英

change in the column value while reading csv in R

I have a csv file having data as follows-

在此处输入图片说明

Now the 3rd column Transaction has String element. Now I want to change the value Dr. to (0) and Cr. to (1) while importing this csv in R using read.csv. Is this possible in R or any trick I can include to make a change in a column while reading csv or I need to write a funcction which will read this particular column and then it will change the value to Dr.(0) and Cr.(1)

As @Stephan showed in his Answer, as.numeric(logical) works well for this case (as would ifelse ), but if you find yourself in a situation where there can be more than 2 values for Transaction , you can create a named vector to use as a mapping

x <- c("Dr.", "Cr.", "Er.", "Cr.")
c(Dr.=0, Cr.=1, Er.=2)[x]
#Dr. Cr. Er. Cr. 
#  0   1   2   1

To make it look more like your example ...

dat <- read.csv("/path/to/file", header=TRUE)
transform(dat, Transaction=c(Dr.=0, Cr.=1)[as.character(Transaction)]) 

You could also do this with the colClasses= argument if you make your own class.

## Sample data
Lines <- "V1,V2
0,Cr.
1,Dr.
2,Cr.
3,Dr.
"

# create a class
setClass("CrDr")
setAs("character", "CrDr", function(from) c(Cr.=1,Dr.=0)[from])
read.csv(text=Lines, colClasses=c("numeric","CrDr"))
#  V1 V2
#1  0  1
#2  1  0
#3  2  1
#4  3  0

You can't do that while reading the data, but once you have read it, the replacement is straightforward:

> Transaction <- factor(sample(c("Dr.","Cr."),10,replace=TRUE))
> Transaction
 [1] Dr. Cr. Cr. Dr. Dr. Cr. Dr. Dr. Dr. Dr.
Levels: Cr. Dr.
> Transaction <- as.numeric(Transaction=="Cr.")
> Transaction
 [1] 0 1 1 0 0 1 0 0 0 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM