R语言 将字符串值转换为数值时出现问题

ca1c2owp  于 2023-04-03  发布在  其他
关注(0)|答案(3)|浏览(178)

抱歉,如果这是一个简单的解决方案,我仍然是新的R
我有一个数据集,它的一些列既包含字符串又包含数字(https://i.stack.imgur.com/MjzvI.png
我想将所有的“-”和“&”字符串值分别转换为-998和-999作为数值,但无法找到实现这一点的解决方案
我试过

df[df=="-"] = -998
df[df=="&"] = -999

但我收到“Error in vec_equal():!无法合并..1..2。”
我也试过把“-998”放在引号里,我想我可以把它转换成数字,但仍然收到同样的错误,同样的事情使用“which”函数

ejk8hzay

ejk8hzay1#

在Tidyverse语法中,您可以尝试

library(tidyverse)

df <- tibble(
  CITY_1 = c("&", "9", "-"),
  STATE_1 = c("57", "5&", "71")
)

df |> 
  mutate(across(everything(), \(x) if_else(str_detect(x, "&"), "-999", x))) |> 
  mutate(across(everything(), \(x) if_else(str_detect(x, "-"), "-998", x)))
#> # A tibble: 3 × 2
#>   CITY_1 STATE_1
#>   <chr>  <chr>  
#> 1 -998   57     
#> 2 9      -998   
#> 3 -998   71

创建于2023年3月30日,使用reprex v2.0.2

8wigbo56

8wigbo562#

stringi::stri_replace_all_regexsprintf一起使用,使事情变得更简单。

cols <- c("V1", "V2", "V3", "V4", "V5")
dat[cols] <- lapply(dat[cols], \(x) as.numeric(
  stringi::stri_replace_all_regex(x, 
                                  pattern=sprintf('.*%s.*', c('-', '&')),
                                  replacement=c(-998, -999), vectorize_all=FALSE)))
dat
#     V1 V2   V3 V4 V5
# 1    9  5   55  1  2
# 2    9  5   57  1  3
# 3    9  5 -999  1  5
# 4 -999  7   71  1  6
# 5 -998  7   71  1  6
# 6 -998  7 -999  1  6
  • 数据:*
dat <- read.table(text='
9 5 55 1 2
9 5 57 1 3
9 5 5& 1 5
& 7 71 1 6
- 7 71 1 6
- 7 5& 1 6
')
e0bqpujr

e0bqpujr3#

另一种基本的R方法,使用@jay.sf的启动dat

dat[sapply(dat, grepl, pattern = "-")] <-  -998
dat[sapply(dat, grepl, pattern = "&")] <-  -999
dat
#     V1 V2   V3 V4 V5
# 1    9  5   55  1  2
# 2    9  5   57  1  3
# 3    9  5 -999  1  5
# 4 -999  7   71  1  6
# 5 -998  7   71  1  6
# 6 -998  7 -999  1  6

或者如果您想要一个代码路径(也许您有更多的模式要重新编码/替换),

ptns <- list("-"=-998, "&"=-999)
Reduce(function(X, i) {
  X[sapply(X, grepl, pattern = names(ptns)[i])] <- ptns[[i]]
  X
}, seq_along(ptns), init = dat)
#     V1 V2   V3 V4 V5
# 1    9  5   55  1  2
# 2    9  5   57  1  3
# 3    9  5 -999  1  5
# 4 -999  7   71  1  6
# 5 -998  7   71  1  6
# 6 -998  7 -999  1  6

在这两种情况下,如果您的模式包含regex特殊字符(包括但不限于.?*[(),则需要对它们进行转义,可能使用stringr::str_escape

相关问题