![](/img/trans.png)
[英]How do I change numeric values in a subset of columns in a R dataframe to other numeric values?
[英]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()
這是使用dplyr
和stringr
包的解決方案。 mutate
允許您修改現有的change_time
變量。 str_remove_all
用於刪除change_time
變量中的匹配模式。 as.numeric
將change_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.