数据框AEbySOC包含两列 - 具有字符级别的因子SOC和整数计数:
> str(AEbySOC)
'data.frame': 19 obs. of 2 variables:
$ SOC : Factor w/ 19 levels "","Blood and lymphatic system disorders",..: 1 2 3 4 5 6 7 8 9 10 ...
$ Count: int 25 50 7 3 1 49 49 2 1 9 ...
SOC的一个级别是空字符串:
> l = levels(AEbySOC$SOC)
> l[1]
[1] ""
我想用非空字符串替换此级别的值,例如“未指定”。这不起作用:
> library(plyr)
> revalue(AEbySOC$SOC, c(""="Not specified"))
Error: attempt to use zero-length variable name
这两个都没有:
> AEbySOC$SOC[AEbySOC$SOC==""] = "Not specified"
Warning message:
In `[<-.factor`(`*tmp*`, AEbySOC$SOC == "", value = c(NA, 2L, 3L, :
invalid factor level, NA generated
实施此方法的正确方法是什么?我感谢任何意见/评论。
答案 0 :(得分:3)
levels(AEbySOC$SOC)[1] <- "Not specified"
创建了一个玩具示例:
df<- data.frame(a= c("", "a", "b"))
df
# a
#1
#2 a
#3 b
levels(df$a)
#[1] "" "a" "b"
levels(df$a)[1] <- "Not specified"
levels(df$a)
#[1] "Not specified" "a" "b"
修改强>
根据OP的评论,如果我们需要根据价值找到它,那么在这种情况下,我们可以尝试
levels(AEbySOC$SOC)[levels(AEbySOC$SOC) == ""] <- "Not specified"
答案 1 :(得分:2)
这样的事情应该有效:
test <- data.frame(a=c("a", "b", "", " "))
str(test)
which.one <- which( levels(test$a) == "" )
levels(test$a)[which.one] <- "NA"
答案 2 :(得分:1)
聚会晚一点,但这是一个整洁的解决方案:
for val in list1:
if val in list2:
#do something
else:
#do something else
这将导致:
library(tidyverse)
df <- data.frame(SOC = c("", "a", "b"))
df <- df %>%
mutate(SOC = fct_recode(SOC, "Not specified" = ""))