0

In order to continue with my preparation of the dataset, I need to make it so the str of each col is numeric instead of chars.

str(eighthr)
'data.frame':   2533 obs. of  74 variables:
 $ Date  : chr  "1/2/1998" "1/3/1998" "1/4/1998" "1/5/1998" ...
 $ WSR0  : chr  "2.8" "2.9" "4.7" "2.6" ...
 $ WSR1  : chr  "3.2" "2.8" "3.8" "2.1" ...
 $ WSR2  : chr  "3.3" "2.6" "3.7" "1.6" ...
 $ WSR3  : chr  "2.7" "2.1" "3.8" "1.4" ...
 $ WSR4  : chr  "3.3" "2.2" "2.9" "0.9" ...
 $ WSR5  : chr  "3.2" "2.5" "3.1" "1.5" ...

How do I convert all rows except $Date?

6
  • 1
    Try with eighthr <- type.convert(eighthr, as.is = TRUE) Did you meant numeric or` integer Commented Jun 9, 2021 at 21:28
  • @akrun that is correct my bad. Commented Jun 9, 2021 at 21:29
  • ok. Please check if that works for you. If there are any non-numeric characters in the columns, it may not work though Commented Jun 9, 2021 at 21:30
  • @akrun it ran, but didnt change when I str(eighthr) Commented Jun 9, 2021 at 21:31
  • I guess you didnt assign <- back Commented Jun 9, 2021 at 21:31

2 Answers 2

2

You can use across in a mutate from dplyr:

library(dplyr)
mutate(eighthr, across(-Date, as.numeric))
Sign up to request clarification or add additional context in comments.

3 Comments

It actually didnt work, when I str() it still says char
Did you assign the result? eighthr <- mutate(eighthr, across(-Date, as.numeric))
I did, its weird, it runs but when I str(eighthr) comes with char
1

I tried henryn solution and it works. You can try copying this code and see if you get errors.

library(dplyr)

data <- data.frame(
  Date = as.character(c('1/2/1998', '1/3/1998')),
  WSR0 = c('2.5', '2.6'),
  WSR1 = c('3.2', '3.5')
)

data2 <- mutate(data, across(-Date, as.numeric))
str(data2)

For whatever reason if the mutate way still doesn't work, you can do a tedious way but surely works which is simply use as.numeric. This should work for sure as it only uses base R command and we can rule out any library issue.

eighthr$WSR0 <- as.numeric(eighthr$WSR0)
eighthr$WSR1 <- as.numeric(eighthr$WSR1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.