【问题标题】:Assign values in table from vector从向量分配表中的值
【发布时间】:2019-01-21 12:13:33
【问题描述】:

在 R 中有一个包含一组昆虫物种的表和一个空列“栖息地特异性”。此外,向量指定那些被认为是栖息地专家的物种:物种 B 和 C 是栖息地专家,物种 A、D 和 E 是栖息地通才。

example.species <- data.frame (species = c("A","B","C","D","E"), habitat.specifity=NA)
example.species
  species habitat.specifity
1       A                NA
2       B                NA
3       C                NA
4       D                NA
5       E                NA
example.specialists <- c("B","C")

我只想在第二列(“栖息地特异性”)中填写“s”代表专家,“g”代表通才。该表应如下所示:

  species  habitat.specifity
1       A                  g
2       B                  s
3       C                  s
4       D                  g
5       E                  g

我认为这一定是一项简单的任务,但我不知道如何完成。任何帮助表示赞赏!

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 试试example.species$habitat.specifity &lt;- ifelse(is.na(match(example.species$species,example.specialists)),"g","s")

标签: r assign


【解决方案1】:

这是基本 R 中的一种简单方法:

example.species <- data.frame (species = c("A","B","C","D","E"), habitat.specifity=NA)
example.species$habitat.specifity <- "g" # default value
example.species$habitat.specifity[example.species$species %in% c("B","C")] <- "s"
#   species habitat.specifity
# 1       A                 g
# 2       B                 s
# 3       C                 s
# 4       D                 g
# 5       E                 g

【讨论】:

  • 这很好用。但是:我确实不时遇到一件事,但老实说不明白:“%”是什么意思?抱歉这个绿色问题...
  • 在 R 中,%op% 形式的运算符称为中缀运算符,%in% 是最常见的一种,还有 %/%%%。您也可以定义自己的。 % 符号在这里本身并没有任何意义。更多信息:datamentor.io/r-programming/infix-operator
【解决方案2】:

dplyr 为例:

library(dplyr)

# Your data
example.species <- data.frame(species = c("A","B","C","D","E"),habitat.specifity=NA)

# Simple if_else with dplyr and pipes
example.species %>%
  mutate(habitat.specifity = if_else(species %in% c("B","C"), "s", "g"))

# Result 
  species habitat.specifity
1       A                 g
2       B                 s
3       C                 s
4       D                 g
5       E                 g

【讨论】:

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