Kevin
Kevin

Reputation: 69

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

Upvotes: 1

Views: 99

Answers (1)

akrun
akrun

Reputation: 887951

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

Upvotes: 2

Related Questions