写入文件后,如何在R中保持从数字到字符的转换

写入文件后,如何在R中保持从数字到字符的转换,r,R,我想将'prop_country_id'转换为'character'数据类型。 因此,我实现了这个转换代码 str(stratified_1) 'data.frame': 60197 obs. of 30 variables: $ srch_id : int 6 52 61 81 106 118 119 139 151 160 ... $ date_time : int 8500 15379 42277 48

我想将'prop_country_id'转换为'character'数据类型。 因此,我实现了这个转换代码

str(stratified_1)

'data.frame':   60197 obs. of  30 variables:
 $ srch_id                    : int  6 52 61 81 106 118 119 139 151 160 ...
 $ date_time                  : int  8500 15379 42277 48907 31091 32805 16006 23669 15969 23629 ...
 $ site_id                    : int  14 16 5 5 5 5 23 24 26 22 ...
 $ visitor_location_country_id: int  100 31 219 219 219 219 181 219 39 92 ...
 $ visitor_hist_starrating    : int  272 272 272 272 272 272 272 272 272 272 ...
 $ visitor_hist_adr_usd       : int  2444 2444 2444 2444 2444 2444 2444 2444 2444 2444 ...
 $ prop_country_id            : int  100 215 219 219 219 219 55 219 202 99 ...
并保存了文件

stratified_1$prop_country_id = as.character(stratified_1$prop_country_id)
str(stratified_1)

'data.frame':   60197 obs. of  30 variables:
 $ srch_id                    : int  6 52 61 81 106 118 119 139 151 160 ...
 $ date_time                  : int  8500 15379 42277 48907 31091 32805 16006 23669 15969 23629 ...
 $ site_id                    : int  14 16 5 5 5 5 23 24 26 22 ...
 $ visitor_location_country_id: int  100 31 219 219 219 219 181 219 39 92 ...
 $ visitor_hist_starrating    : int  272 272 272 272 272 272 272 272 272 272 ...
 $ visitor_hist_adr_usd       : int  2444 2444 2444 2444 2444 2444 2444 2444 2444 2444 ...
 $ prop_country_id            : chr  "100" "215" "219" "219" ...
然而,当我读回文件时,“prop_country_id”又是“integer”

write.csv(stratified_1, "train.csv", row.names = FALSE) 

如何将“prop\u country\u id”作为字符保存文件

这可能会有帮助。。。在csv中读取时,可以指定列的类别:

stratified_1 = read.csv("train.csv", header = TRUE)
str(stratified_1)

'data.frame':   60197 obs. of  30 variables:
 $ srch_id                    : int  6 52 61 81 106 118 119 139 151 160 ...
 $ date_time                  : int  8500 15379 42277 48907 31091 32805 16006 23669 15969 23629 ...
 $ site_id                    : int  14 16 5 5 5 5 23 24 26 22 ...
 $ visitor_location_country_id: int  100 31 219 219 219 219 181 219 39 92 ...
 $ visitor_hist_starrating    : int  272 272 272 272 272 272 272 272 272 272 ...
 $ visitor_hist_adr_usd       : int  2444 2444 2444 2444 2444 2444 2444 2444 2444 2444 ...
 $ prop_country_id            : int  100 215 219 219 219 219 55 219 202 99 ...

确保您在创建和读取csv StringsAsAffactors=FALSEhmm时具有此选项,它对我有效:/这意味着您根本不必执行转换为字符的部分,您只需在每次读取文件时指定字符即可。对不起,我会继续思考,但我不知道为什么这对你不起作用。哦,它起作用了!谢谢我把它错当成write.cvs了。嗯,我实际上想在另一个程序(weka)中使用该文件,所以它解决了R中的问题,但文件本身仍然是数字数据类型。。。无论如何,非常感谢你!
stratified_1 = read.csv("train.csv", header = TRUE, colClasses=c("prop_country_id"="character"))