-1

The data is as under.

 r
  V1 V2 V3 V4 V5
1  C  1  1  0 16
2  A  1  1 16  0
3  A  1  1 16  0
class(r)
[1] "data.frame"
class(r[,2])
character

I change 2 till 5 column into numeric with four statement.

as.numeric(r[,2])->r[,2]
as.numeric(r[,3])->r[,3]
as.numeric(r[,4])->r[,4]
as.numeric(r[,5])->r[,5]

How can I change it with just one statement?

zx8754
  • 52,746
  • 12
  • 114
  • 209
showkey
  • 482
  • 42
  • 140
  • 295
  • 3
    You're working with a matrix. in every R introduction is mentioned that a matrix can hold only a single type (in this case character as you have letters). If you want to do this, use a data frame. – Joris Meys Jan 02 '14 at 10:02
  • http://stackoverflow.com/questions/2288485/how-to-convert-a-data-frame-column-to-numeric-type : another duplicate – Joris Meys Jan 02 '14 at 11:08

1 Answers1

1

You can use lapply to convert the columns you want to convert.

Your starting data (possibly):

r
#   V1 V2 V3 V4 V5
# 1  C  1  1  0 16
# 2  A  1  1 16  0
# 3  A  1  1 16  0
str(r)
# 'data.frame':  3 obs. of  5 variables:
#  $ V1: chr  "C" "A" "A"
#  $ V2: chr  "1" "1" "1"
#  $ V3: chr  "1" "1" "1"
#  $ V4: chr  "0" "16" "16"
#  $ V5: chr  "16" "0" "0"

Convert all columns except the first to numeric:

r[-1] <- lapply(r[-1], as.numeric)
r
#   V1 V2 V3 V4 V5
# 1  C  1  1  0 16
# 2  A  1  1 16  0
# 3  A  1  1 16  0
str(r)
# 'data.frame': 3 obs. of  5 variables:
#  $ V1: chr  "C" "A" "A"
#  $ V2: num  1 1 1
#  $ V3: num  1 1 1
#  $ V4: num  0 16 16
#  $ V5: num  16 0 0
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • i revise a bug,it must be **r[,-1] <- data.frame(lapply(r[,-1], as.numeric))**. – showkey Jan 02 '14 at 12:03
  • 2
    @it_is_a_literature, your revision is unnecessary. My solution works as presented if you are working with `data.frame`s because of how `[` works on `list`s. If you had a `matrix`, indeed you would need to use `[, -1]` instead of `[-1]`. And, you don't need to wrap your `lapply` in `data.frame`. – A5C1D2H2I1M1N2O1R2T1 Jan 02 '14 at 13:30