【问题标题】:How to do a complex search in a dataframe in R?如何在 R 中的数据框中进行复杂搜索?
【发布时间】:2017-10-24 18:35:57
【问题描述】:

我有一个包含 14 列的数据框。这 14 列中的 2 列是“区域”和“人口密度”。假设我想查找区域为 4 时的所有实例,并打印出每个区域 = 4 实例的人口密度值。

在这里,我将在数据框中添加一个名为“PopDens”的新列 这个新列将把总人口除以 陆地区域

    cdi.df$PopDens= cdi.df$TotalPop/cdi.df$LandArea
    dim(cdi.df) #here I verify the columns are now 14 and not 13
    head(cdi.df) #here I verify that the name and calculations are correct
    head(cdi.df$PopDens, 3) #here I return only the first three values 

当 region 为 =4 时,有没有办法只返回 pop dens 的值?

【问题讨论】:

  • 您想要区域为 4 的所有列吗?或者您只是想要一个人口密度的向量,该地区的人口密度为 4?无论哪种方式,这绝不是一个“复杂”的搜索。

标签: r rscript


【解决方案1】:

就像这样:

cdi.df[cdi.df$Region==4,] #to see the data.frame with only region 4
cdi.df$PopDens[cdi.df$Region==4] #to see only the population densities

下一次,请提供可重现的示例,如 here 所述。

【讨论】:

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