简体   繁体   中英

Convert the factor to numeric in R

I have a data and i use read.table(...) in to r. and let w<-read.table(...)

>w
  V1 V2 
1 10 1,000
2  9 2,000

because of the comma in 1,000 2,000 and i found

>class(V2)
[1]"factor"
>class(V1)
[1]"interger"

how could i do in R to convert V2 to interger 1000 2000 directly

not to change the data in .txt

i try

>as.numeric(as.character(w))

but it not successiful

We can remove the , with gsub and convert to numeric class

w$V2 <- as.numeric(gsub(',', '', w$V2))
str(w)
# 'data.frame': 2 obs. of  2 variables:
# $ V1: int  10 9
# $ V2: num  1000 2000

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