【问题标题】:Add variable to dataframe in specific rows based on a name in that row R根据该行 R 中的名称将变量添加到特定行中的数据框
【发布时间】:2018-09-07 02:47:41
【问题描述】:

我正在尝试在此地图数据框中添加与特定国家相对应的特定变量。

library(maps)

countries <- c("Australia", "South Africa", "India", "Mexico", "USA", "Russia")
genes <- c("gene1","gene2","gene3","gene4","gene5","gene6")

bounds <- map("world", countries, fill = TRUE, plot = FALSE)

bounds$genes <- genes

但是,这只是添加了一列“基因”并将变量放在前六行中,而不是对应的国家/地区。所以如果我打电话给印度,它应该返回gene3。我在 StackOverflow 中找不到一个简单的解决方案。

【问题讨论】:

    标签: r dataframe append


    【解决方案1】:

    你可以做这样的事情......

    bounds$genes <- genes[match(gsub("\\:.*", "", bounds$names), countries)]
    

    bounds$names 的格式为country:region,因此gsub 会删除: 之后的位,然后match 返回相应的索引。

    【讨论】:

    • 是的,这确实有效,非常感谢,如此简单的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多