【问题标题】:How to convert a string of as.factor to as.numeric in R?如何在 R 中将 as.factor 的字符串转换为 as.numeric?
【发布时间】:2018-05-15 02:03:35
【问题描述】:

我有一个数据集如下:

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

我有大约 400 行这样的行。该键具有像 t0, t01, t03, t100 这样的值,它们表示以天为单位的时间,例如。 t0 为 0 天,t01 为第 1 天,t100 为第 100 天。

目前key的结构是as.factor

我需要将密钥转换为as.numeric 函数,使其读取为0,1,2...100。对于每个样本,都有几个关联的 t0s、t1s 等。有没有一种简单的方法可以在不手动替换所有 t0、t1 .. 等的情况下做到这一点?

【问题讨论】:

  • 你不能用空字符串(sub('t', '', df$key))替换t,然后转换为as.numeric 吗?
  • 干得不错!完美。

标签: r vector numeric


【解决方案1】:

你可以用gsub代替。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2022-12-06
    • 2018-04-06
    • 1970-01-01
    • 2014-04-29
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多