Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am working on the below data:

 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 have changed 2nd column into numeric using the code below:

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

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

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

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

Can I change it with only one statement?

1 Answer

0 votes
by (36.8k points)

Use lappy to convert the columns which you want to convert.

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"

Here is the code to 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

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...