首页 > 解决方案 > 如何替换 R 中非数字列表中的逗号?

问题描述

我在 R 中有一个 data.frame,它也是一个列表。我想用“。”替换“,”。在数字中。data.frame 不是数字的,但我认为它必须能够更改小数分隔符。

我尝试了很多,但没有任何效果。我不想重新排列或操作我的 data.frame。我想要的只是摆脱十进制数字中的“,”。

df <- data.frame(colnames(c("a","b","c")),"row1"=c("2,3","6"),"row2"=c("56,0","56,8"),"row3"=c("1",0"))

#trials to make df numeric and change from , to .

as.numeric(str_replace_all(df,",","."))
as.numeric(unlist(df[ ,2:3]))
lapply(df, as.numeric)
as.numeric(gsub(pattern = ",",replacement = ".",df[ ,2:3]))
as.numeric(df$a)

对于这个讨厌的问题,我还能做些什么呢?

标签: rdataframenumeric

解决方案


我们也可以使用mutate_all

library(dplyr)
library(stringr)
df %>%
    mutate_all(~ as.numeric(str_replace(., ",", ".")))

推荐阅读