![](/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.