简体   繁体   中英

R convert csv file to data frame

I use the code

 x<-read.csv(filename,sep="\t",head=TRUE)   
 x<-x[,-3] 

get the data like this:

14:59:46  16.10         96     154560 买盘  
14:59:41  16.10          1       1610 买盘  
14:59:36  16.09          2       3218 买盘  
14:59:21  16.09          3       4827 买盘  
14:59:21  16.10         15      24150 买盘    
14:59:16  16.03         32      51296 卖盘  

how can i convert this data frame like this:

14:59:46  16.10         96     154560 1  
14:59:41  16.10          1       1610 1  
14:59:36  16.09          2       3218 1  
14:59:21  16.09          3       4827 1  
14:59:21  16.10         15      24150 1  
14:59:16  16.03         32      51296 -1  

That is: the string "买盘" instead of 1, the string "卖盘" instead of -1

If there are only two different strings in the 5th column of x , you can use

x[[5]] <- (-1) ^ (x[[5]] == "卖盘")

The result:

#         V1    V2 V3     V4 V5
# 1 14:59:46 16.10 96 154560  1
# 2 14:59:41 16.10  1   1610  1
# 3 14:59:36 16.09  2   3218  1
# 4 14:59:21 16.09  3   4827  1
# 5 14:59:21 16.10 15  24150  1
# 6 14:59:16 16.03 32  51296 -1

How it works?

The command x[[5]] == "卖盘" creates a logical vector (ie, FALSE and TRUE ). If logical vectors are used with mathematical functions (here: ^ ), they are cast into numeric vectors of 0 s and 1 s. -1 ^ 0 = 1 and -1 ^ 1 = -1.

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