简体   繁体   English

R:字符变量在cbind()和data.frame()之后变为数字

[英]R: Character variable becomes numeric after cbind() and data.frame()

I try to combine one column with a data.frame. 我尝试将一列与data.frame结合起来。 I used both cbind() and data.frame(), but after that the character variable became a numeric one. 我同时使用了cbind()和data.frame(),但之后字符变量变成了数字变量。

>is.character(new_listing_zip)
[1] TRUE
> new_race_disp_use2 <- cbind(new_listing_zip,opo_trans) 
> is.character(new_race_disp_use2$new_listing_zip)
[1] FALSE

> is.character(new_listing_zip)
[1] TRUE
> new_race_disp_use2 <- data.frame(new_listing_zip,opo_trans) 
> is.character(new_race_disp_use2$new_listing_zip)
[1] FALSE

Does anyone could help me with this? 有人可以帮我吗? Thank you. 谢谢。

if you check the help files for data.frame() I think you will find your answer 如果您查看帮助文件中的data.frame(),我想您会找到答案的

 ?data.frame

You'll want to set your 您需要设置

options(stringsAsFactors = TRUE)

to change it globally or just set your parameter for 全局更改它,或只是为

stringsAsFactors = TRUE

when declaring your data.frame, assuming these are actual character strings. 在声明data.frame时,假设它们是实际的字符串。 Otherwise I would simply declare your variable as a factor when joining it 否则,我只是在加入变量时将变量声明为一个因素

new_race_disp_use2 <- cbind(factor(new_listing_zip),opo_trans)

Now of course if your 'factor' is actually a numeric you want as a string (seemingly zip codes in your example) you'll want to either set your zip codes as strings to begin with using quotes (ie "12345") or set the data type after the data.frame is built 现在当然,如果您的“因子”实际上是您想要作为字符串的数字(在您的示例中似乎是邮政编码),则需要将邮政编码设置为字符串,以使用引号(例如“ 12345”)开始或建立data.frame之后的数据类型

 new_race_disp_use$new_listing_zip <- as.character(new_race_disp$new_listing_zip)

or 要么

as.factor(varName) 

or simply 或简单地

factor() instead of as.character()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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