代码之家  ›  专栏  ›  技术社区  ›  Geomicro

缩放df,但它不是数字?

  •  1
  • Geomicro  · 技术社区  · 2 年前

    我有一个环境测量的df(称为env),我希望通过使用以下代码进行缩放:

    scale.env <- scale(env, center=TRUE, scale=TRUE)
    

    但我发现了错误

    scale.env <- scale(env, center=TRUE,scale=TRUE)
    Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric
    

    我试图将env转换为数字,但收到了相同的错误。

    env <-lapply(env, as.numeric)
    > str(env)
    List of 5
     $ X00940_Cl_mg_per_L        : num [1:282] 0.3 0.31 0.31 1.83 2 ...
     $ X00945_SO4_mg_per_L_as_SO4: num [1:282] 9.8 8.03 8.62 6.53 6.66 ...
     $ X71851_NO3_mg_per_L_as_NO3: num [1:282] 0.19 0.23 0.23 NA NA NA NA 0.96 0.38 6.43 ...
     $ X00950_F_mg_per_L         : num [1:282] 0.07 0.07 0.06 0.07 0.08 NA 0.13 0.16 0.16 NA ...
     $ X00602_TN_mg_per_L_as_N   : num [1:282] 1.19 0.58 0.65 0.8 0.74 NA 0.7 1.44 1.12 1.55 ...
    

    敬请见识!! 请注意,下面的dput是在我转换为数字之前。

    dput(env)
    structure(list(X00940_Cl_mg_per_L = c("0.3", "0.31", "0.31", 
    "1.83", "2"), X00945_SO4_mg_per_L_as_SO4 = c(9.8, 8.03, 8.62, 
    6.53, 6.66), X71851_NO3_mg_per_L_as_NO3 = c("0.19", "0.23", "0.23", 
    NA, NA), X00950_F_mg_per_L = c("0.07", "0.07", "0.06", "0.07", 
    "0.08"), X00602_TN_mg_per_L_as_N = c("1.19", "0.58", "0.65", 
    "0.8", "0.74")), row.names = c(NA, -5L), class = c("tbl_df", 
    "tbl", "data.frame"))
    
    2 回复  |  直到 2 年前
        1
  •  2
  •   Allan Cameron    2 年前

    如果要将Lappy生成的数据写回数据帧,请使用 [] 符号这将保留数据框的属性

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

    那你就可以

    scale(env, center = TRUE, scale = TRUE)
    
        2
  •  1
  •   Mohamed Desouky    2 年前

    使用 data.frame 之后 lapply

    env <- data.frame(lapply(env, as.numeric))
    
    # then scale
    
    scale.env <- scale(env, center=TRUE, scale=TRUE)