【问题标题】:How to make factor names appear in ifelse statement in R?如何使因子名称出现在 R 的 ifelse 语句中?
【发布时间】:2018-07-19 17:49:54
【问题描述】:

我必须关注数据集。我想创建一个列,以便如果 unid 列中有一个数字,那么在 dat$identification 中我希望它说“未识别”,否则我希望它打印物种列中的任何内容。所以最终输出应该看起来像 dat$identificaiton x,y,unidentified,unidentified。使用此代码,它显示1,2,unidentified,unidentified

请注意,出于其他目的,我只想将 unid 列用于 ifelse 语句的 !(is.na) 部分,而不是物种。

unid <- c(NA,NA,1,4)
species <- c("x","y",NA,NA)
df <- data.frame(unid, species)
df$identification <- ifelse(!is.na(unid), "unidentified", df$species)

#Current Output of df$identification: 
1,2,unidentified,unidentified

#Needed Output
x,y,unidentified,unidentified

【问题讨论】:

  • ifelse 中使用as.character(df$species) 强制转换为字符。
  • 太棒了!如果您可以将其发布为答案,我可以正式投票。
  • 请查看答案的编辑。我认为这值得您花时间。

标签: r if-statement


【解决方案1】:

你可以强制类'factorto classcharacterin theifelse`的列。

df$identification <- ifelse(!is.na(unid), "unidentified", as.character(df$species))

df
#  unid species identification
#1   NA       x              x
#2   NA       y              y
#3    1    <NA>   unidentified
#4    4    <NA>   unidentified

编辑。

在 OP 接受答案后,我提醒自己 ifelse 速度慢,索引速度快,因此我使用更大的数据集进行了测试。

首先,看看两种解决方案是否产生相同的结果:

df$id1 <- ifelse(!is.na(unid), "unidentified", as.character(df$species))

df$id2 <- "unidentified"
df$id2[is.na(unid)] <- species[is.na(unid)]

identical(df$id1, df$id2)
#[1] TRUE

结果是一样的。

现在时间他们都使用包microbenchmark

n <- 1e4
df1 <- data.frame(unid = rep(unid, n), species = rep(species, n))

microbenchmark::microbenchmark(
  ifelse = {df1$id1 <- ifelse(!is.na(df1$unid), "unidentified", as.character(df1$species))},
  index = {df1$id2 <- "unidentified"
           df1$id2[is.na(df1$unid)] <- species[is.na(df1$unid)]
          },
  relative = TRUE
)
#Unit: nanoseconds
#    expr      min       lq        mean   median         uq      max  neval cld
#  ifelse 12502465 12749881 16080160.39 14365841 14507468.5 85836870    100   c
#   index  3243697  3299628  4575818.33  3326692  4983170.0 74526390    100   b 
#relative       67       68      208.89      228      316.5      540    100   a 

平均而言,索引速度提高了 200 倍。为ifelse 编写两行代码而不是只写一行代码是非常值得的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    相关资源
    最近更新 更多