替换逗号转换为数字并引入NA,如果r中有字符输入

发布于 2025-02-13 19:25:44 字数 477 浏览 0 评论 0原文

我有一个数据框架DF,其中很少有逗号和字符值。我想删除逗号并用空白替换字符值。但想保留Col5。我应该仅将Col1转换为COL4为数字并删除逗号。

col1=c(1,45,30,35)
col2=c(33,"33,345",87,89)
col3=c("67,345",77,90,"reply")
col4=c("silver",43,23,55)
col5=c("gb","rt","dc","ty")

DF=data.frame(col1,col2,col3,col4,col5)

col6=c(1,45,30,35)
col7=c(33,33345,87,89)
col8=c(67345,77,90,"")
col9=c("",43,23,55)
col10=c("gb","rt","dc","ty")

DF_Output=data.frame(col6,col7,col8,col9,col10)

我的预期输出就像df_output。请帮助我解决这个问题。

I have a data frame DF in which few columns are having comma and character values in it. I want to remove comma and replace character values with blank. But want to retain col5 as it is. I should convert only col1 to col4 to numeric and remove comma.

col1=c(1,45,30,35)
col2=c(33,"33,345",87,89)
col3=c("67,345",77,90,"reply")
col4=c("silver",43,23,55)
col5=c("gb","rt","dc","ty")

DF=data.frame(col1,col2,col3,col4,col5)

col6=c(1,45,30,35)
col7=c(33,33345,87,89)
col8=c(67345,77,90,"")
col9=c("",43,23,55)
col10=c("gb","rt","dc","ty")

DF_Output=data.frame(col6,col7,col8,col9,col10)

My expected output is like DF_Output. Please help me to solve this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

再见回来 2025-02-20 19:25:44

您可以尝试

library(dplyr)
library(stringr)

DF %>%
  mutate(across(col1:col4, ~as.numeric(str_remove(.x, ","))))
  col1  col2  col3 col4 col5
1    1    33 67345   NA   gb
2   45 33345    77   43   rt
3   30    87    90   23   dc
4   35    89    NA   55   ty

You may try

library(dplyr)
library(stringr)

DF %>%
  mutate(across(col1:col4, ~as.numeric(str_remove(.x, ","))))
  col1  col2  col3 col4 col5
1    1    33 67345   NA   gb
2   45 33345    77   43   rt
3   30    87    90   23   dc
4   35    89    NA   55   ty
偷得浮生 2025-02-20 19:25:44

您可以从read> readr软件包中使用parse_number

cbind(apply(DF[1:4], 2, readr::parse_number),
      DF[5]
)

#   col1  col2  col3 col4 col5
# 1    1    33 67345   NA   gb
# 2   45 33345    77   43   rt
# 3   30    87    90   23   dc
# 4   35    89    NA   55   ty

You can use parse_number from readrpackage as well:

cbind(apply(DF[1:4], 2, readr::parse_number),
      DF[5]
)

#   col1  col2  col3 col4 col5
# 1    1    33 67345   NA   gb
# 2   45 33345    77   43   rt
# 3   30    87    90   23   dc
# 4   35    89    NA   55   ty
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文