[英]change in the column value while reading csv in R
I have a csv file having data as follows- 我有一个csv文件,其数据如下:
Now the 3rd column Transaction has String element. 现在,第三列Transaction具有String元素。 Now I want to change the value Dr. to (0) and Cr. 现在,我想将值Dr.更改为(0)和Cr。 to (1) while importing this csv in R using read.csv. (1),同时使用read.csv在R中导入此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) 这在R中是可行的还是在读取csv时我可以包括在列中进行更改的任何技巧,或者我需要编写一个函数来读取该特定列,然后将其值更改为Dr.(0)和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 正如@Stephan在他的答案中所示, as.numeric(logical)
在这种情况下效果很好( ifelse
也会ifelse
),但是如果您发现自己处于Transaction
可以有两个以上值的情况,则可以创建一个命名向量用作映射
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. 如果您自己创建类,也可以使用colClasses=
参数来执行此操作。
## 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.