user8435999
user8435999

Reputation:

How to convert a string of as.factor to as.numeric in R?

I have a data set as follows:

sample tmt key value
1       1   t0  11
1       2   t0  12
..
..
100     4   t100 121

I have ~400 such rows. The key has values like t0, t01, t03, t100 that represent time in days eg. t0 is 0 days, t01 is day 1, t100 is day 100.

Currently the structure of the key is as.factor

I need to convert the key into a as.numeric function such that it reads as 0,1,2...100. For each sample there are several associated t0s, t1s etc. Is there an easy way to do it without manually replacing all the t0, t1 .. etc?

Upvotes: 0

Views: 296

Answers (1)

Kevin Arseneau
Kevin Arseneau

Reputation: 6264

You can use gsub to substitute.

library(dplyr)

df <- tibble(
  sample = 1:100,
  tmt = 1:100,
  key = as.factor(paste0("t", 1:100)),
  value = rnorm(100)
)

df %>% mutate(key = as.numeric(gsub("t", "", key)))

# # A tibble: 100 x 4
#    sample   tmt   key       value
#     <int> <int> <dbl>       <dbl>
#  1      1     1     1 -1.92796670
#  2      2     2     2  0.32439762
#  3      3     3     3 -1.09627047
#  4      4     4     4 -0.11293941
#  5      5     5     5 -1.33618028
#  6      6     6     6  0.26458634
#  7      7     7     7 -0.31001779
#  8      8     8     8 -0.76220697
#  9      9     9     9  0.09226835
# 10     10    10    10  1.27032132

Upvotes: 3

Related Questions