【问题标题】:Replace NA in Column A, comparing column A and a list替换 A 列中的 NA,比较 A 列和列表
【发布时间】:2017-12-05 06:43:10
【问题描述】:

我有一个包含两列的 data.frame DF。名称和分数。 我有一个包含名称的列表(the.list)。有些等于 DF$names 中名称中的名称。 我需要在 DF$score 中插入一个数字(2000),如果名称在.list 中并且分数为 NA

数据:

DF.scores <- data.frame(c("steve", "anna", "albert", "john", "sarah", "lily"), c(2000, 1500, NA, NA, NA, 1750))
names(DF.scores) <- c("names", "score")
the.list <- c("anna", "steve", "john")  

我需要数据框这样结束:

names   score
steve   2000
anna    1500
albert  NA
john    2000
sarah   NA
lily    1750

我已尝试对数据进行子集化,使用 which 命令但没有得到任何结果。

【问题讨论】:

  • ...替换表格中的DF.scores$score[DF.scores$names %in% the.list] &lt;- 2000
  • 我认为上述建议没有解决OP将分数设置为2000的标准,即if the name is in the.list and the score is NA

标签: r


【解决方案1】:

我知道这很简单,但是如果您的数据框中已经有您可能不想更改的分数,那么很难击败一个简单的 ifelse 语句:

DF.scores$score <- with(DF.scores,ifelse(names %in% the.list & is.na(score),yes=2000,no=score))

【讨论】:

  • 我不认为这个答案解决了OP将分数设置为2000的标准,即if the name is in the.list and the score is NA
  • @Snubian 谢谢...我错过了第二个条件。编辑将很快发布。
【解决方案2】:

考虑为此使用dplyr::mutate()

dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))

如果两个条件都满足,这会将分数设置为 2000,namesthe.list并且 scoreNA

> dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))
   names score
1  steve  2000
2   anna  1500
3 albert    NA
4   john  2000
5  sarah    NA
6   lily  1750

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 2021-06-10
    • 2021-06-27
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多