我有一个包含数字和文本的结果数据列表。
示例数据:
df$col_1
Neg
Negative
32
16
64
8
128
4
not done
Pos
Missing
?Pos
~2
? 240
Run Code Online (Sandbox Code Playgroud)
我所做的是创建一个新列并尝试重新编码数据。
df$col <- NA df$col [ which (df$col_1=="Positive" )] <- 1
df$col [ which (df$col_1=="2" )] <- 1
df$col [ which (df$col_1=="Negative" )] <- 1
Run Code Online (Sandbox Code Playgroud)
不是像上面那样对每个可能的组合进行编码,我想做的是能够创建一个包含负数、正数和 NA 值的列表。
我试过这个
list <- c ("2","4","8","16","32")
df$col [ which (df$col_1=="list" )] <- 1
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
除非有问号,否则每个数字都应被视为正数。所以我想知道我是否可以将所有数字转换为数字?
对于所有的杂文,除了正面和负面之外,我想放NA。
df$col_1 df$col
Neg 0
Negative 0
32 1
16 1
64 1
8 1
128 1
4 1
not done NA
Pos 1
Missing NA
?Pos NA
~2 1
? 240 NA
Run Code Online (Sandbox Code Playgroud)
您可能有一组相当复杂的条件,因此最好将正则表达式与ifelse和 一起使用sapply。例如,下面我grepl在嵌套ifelses 中使用:
df$col <- sapply(df$col_1,
function(x) ifelse(grepl("^((~)?\\d+)$|^([pP]os(itive)?)$", x),
1,
ifelse(grepl("^[nN]eg(ative)?$", x), 0, NA)
)
)
#### OUTPUT ####
col_1 col
1 Neg 0
2 Negative 0
3 32 1
4 16 1
5 64 1
6 8 1
7 128 1
8 4 1
9 not done NA
10 Pos 1
11 Missing NA
12 ?Pos NA
13 ~2 1
14 ? NA
15 240 1
Run Code Online (Sandbox Code Playgroud)
说明:如果字符串只包含数字,有或没有前面的 tilda ~,或者只有“Pos”或“Positive”,返回 1。否则返回第二个的输出,ifelse如果字符串只包含“Neg”或“Negative” ,则返回 0 ”,否则NA。
df <- structure(list(col_1 = c("Neg", "Negative", "32", "16", "64",
"8", "128", "4", "not done", "Pos", "Missing", "?Pos", "~2",
"?", "240")), class = "data.frame", row.names = c(NA, -15L))
Run Code Online (Sandbox Code Playgroud)