是否有一种方法可以用NA
或零替换破折号,而不会影响类似于以下内容的向量c("-","-121512","123","-")
中的负值。
答案 0 :(得分:2)
就做
x <- c("-","-121512","123","-")
x[x == "-"] <- NA
x
#[1] NA "-121512" "123" NA
如果您需要数字矢量来代替x
中的字符换行as.numeric()
。
如果您要替换数据框中的所有"-"
,我们可以使用相同的逻辑
df1 <- data.frame(x = c("-","-121512","123","-"),
y = c("-","-121512","123","-"),
z = c("-","A","B","-"), stringsAsFactors = FALSE)
df1[df1 == "-"] <- NA
如果需要数字列,则type.convert
df1[] <- lapply(df1, type.convert, as.is = TRUE)
str(df1)
'data.frame': 4 obs. of 3 variables:
$ x: int NA -121512 123 NA
$ y: int NA -121512 123 NA
$ z: chr NA "A" "B" NA
答案 1 :(得分:1)
我们可以使用na_if
library(dplyr)
na_if(v1, "-") %>%
as.numeric
#[1] NA -121512 123 NA
如果它是data.frame
library(tidyverse)
df1 %>%
mutate_all(na_if, "-") %>%
type_convert
v1 <- c("-","-121512","123","-")