【问题标题】:How to convert string based data frame to numeric [duplicate]如何将基于字符串的数据框转换为数字[重复]
【发布时间】:2017-05-12 08:33:15
【问题描述】:

我有以下数据框:


df <- structure(list(Foo.ID.6hr.SP = c("0.00261", "0.00271", "0.00281", 
"0.00258", "0.00281", "0.00305"), Foo.IP.6hr.SP = c("0.00439", 
"0.00496", "0.00469", "0.00437", "0.00454", "0.00418"), LPS.IV.SP = c("0.00294", 
"0.00290", "0.00267", "0.00278", "0.00288", "0.00295"), MPL.IV.SP = c("0.00335", 
"0.00326", "0.00292", "0.00318", "0.00321", "0.00329")), .Names = c("Foo.ID.6hr.SP", 
"Foo.IP.6hr.SP", "LPS.IV.SP", "MPL.IV.SP"), row.names = c("B_Fo_LN", 
"B_Fo_MLN", "B_Fo_PC", "B_Fo_Sp", "B_FrE_BM", "B_FrE_FL"), class = "data.frame")

df
#>          Foo.ID.6hr.SP Foo.IP.6hr.SP LPS.IV.SP MPL.IV.SP
#> B_Fo_LN        0.00261       0.00439   0.00294   0.00335
#> B_Fo_MLN       0.00271       0.00496   0.00290   0.00326
#> B_Fo_PC        0.00281       0.00469   0.00267   0.00292
#> B_Fo_Sp        0.00258       0.00437   0.00278   0.00318
#> B_FrE_BM       0.00281       0.00454   0.00288   0.00321
#> B_FrE_FL       0.00305       0.00418   0.00295   0.00329


str(df)
#> 'data.frame':    6 obs. of  4 variables:
#>  $ Foo.ID.6hr.SP: chr  "0.00261" "0.00271" "0.00281" "0.00258" ...
#>  $ Foo.IP.6hr.SP: chr  "0.00439" "0.00496" "0.00469" "0.00437" ...
#>  $ LPS.IV.SP    : chr  "0.00294" "0.00290" "0.00267" "0.00278" ...
#>  $ MPL.IV.SP    : chr  "0.00335" "0.00326" "0.00292" "0.00318" ...

str(df) the value is inchr`所示。如何转换为数字?

我试过了,但是行名不见了:

> as.data.frame(sapply(df,as.numeric))
  Foo.ID.6hr.SP Foo.IP.6hr.SP LPS.IV.SP MPL.IV.SP
1       0.00261       0.00439   0.00294   0.00335
2       0.00271       0.00496   0.00290   0.00326
3       0.00281       0.00469   0.00267   0.00292
4       0.00258       0.00437   0.00278   0.00318
5       0.00281       0.00454   0.00288   0.00321
6       0.00305       0.00418   0.00295   0.00329

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以的

    df[] <- lapply(df, as.numeric)
    

    或使用dplyr

    library(dplyr)
    df %>%
      mutate_all(as.numeric) 
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2020-01-24
      • 2018-10-04
      • 2018-02-26
      • 1970-01-01
      • 2018-01-02
      • 2021-09-12
      • 2022-01-13
      • 2020-04-01
      相关资源
      最近更新 更多