簡體   English   中英

如何在 r 中將值更改為數字?

[英]How do I change values to numeric in r?

可重現的樣本數據

df <- data.frame(
  change_time = c("[4605]", "[4000]", "[4305]", 
                  "[5530]", "[6500]", "[5653]", 
                  "[2936]", "[4691]", "[2500]")
)

帶值的數據框

嗨,我如何將值更改為數字? 到目前為止,我已經使用 as.numeric(),但我收到警告警告消息:強制引入的 NA

在處理 R object 時,明智的做法是使用 str() function 查看您擁有的數據類型。 我不確定,但我假設您的數據是每邊帶有 [ ] 的字符串。

 #Install from tidyverse or manually
library(magrittr)
library(stringr)
str_extract(df$change_time,"\\d*") %>% as.numeric()

這是使用dplyrstringr包的解決方案。 mutate允許您修改現有的change_time變量。 str_remove_all用於刪除change_time變量中的匹配模式。 as.numericchange_time變量從character轉換為numeric

df替換為數據集的名稱。

# Recreate sample data 

df <- data.frame(
  change_time = c("[4605]", "[4000]", "[4305]", "[5530]", "[6500]", "[5653]", "[2936]", "[4691]", "[2500]")
)

# Import the libraries

library(dplyr)
library(stringr)

# Code to accomplish what is asked

df %>% 
  mutate(
    change_time = as.numeric(str_remove_all(change_time, "\\[|\\]"))
    )

# Output

#>   change_time
#> 1        4605
#> 2        4000
#> 3        4305
#> 4        5530
#> 5        6500
#> 6        5653
#> 7        2936
#> 8        4691
#> 9        2500

reprex package (v0.3.0) 於 2021 年 3 月 11 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM