【问题标题】:Using value in Specific Row to Filter the Columns in R使用特定行中的值过滤 R 中的列
【发布时间】:2019-06-19 18:26:10
【问题描述】:

我必须根据行的特定值对数据框进行子集化。这意味着如果必须以包含大于 10 的值的行作为条件来提取该行中满足条件的所有列。

这是我的数据样本。

structure(list(`Copper ores and concentrates; copper mattes, cemen` = c(200.53, 
274.84, 1.37, 376.686907694609), `Fabrics, woven, of man-made fabrics` = c(4093.12, 
1184.47, 0.29, 342.762777758776), Copper = c(44.76, 91.45, 2.04, 
186.843219392315), Zinc = c(80.14, 110.73, 1.38, 152.996417519341
), `Waste, parings and scrap, of plastics` = c(590.3, 286.3, 
0.49, 138.857682534305), `Fixed vegetable fats & oils, crude, refined, fract.` = c(864.14, 
344.63, 0.4, 137.44281817761), `Sulphur and unroasted iron pyrites` = c(23.99, 
55.11, 2.3, 126.599087119633), `Radio-actives and associated materials` = c(48.59, 
76.67, 1.58, 120.977338958633), `Rails & railway track construction mat., iron, steel` = c(464.66, 
214.76, 0.46, 99.259367279301), `Iron ore and concentrates` = c(46.91, 
67.8, 1.45, 97.9927520784481), `Crude vegetable materials, n.e.s.` = c(164.46, 
123.26, 0.75, 92.3812939316551), `Other plastics, in primary forms` = c(187.76, 
124.21, 0.66, 82.169386983383), `Crude animal materials, n.e.s.` = c(43.08, 
56.52, 1.31, 74.1529805013928), `Pig iron & spiegeleisen, sponge iron, powder & granu` = c(17.17, 
33.03, 1.92, 63.5399475829936), `Ores and concentrates of base metals, n.e.s.` = c(15.7, 
27.6, 1.76, 48.5197452229299), `Furskins, tanned or dressed, excluding those of 8483` = c(178.49, 
75.12, 0.42, 31.6152972155303), `Metalworking machinery (excludingmachine-tools) & parts` = c(179.18, 
71.69, 0.4, 28.6832018082375)), row.names = c("SD", "Mean", "INTENSITY", 
"INTENSITY2"), class = "data.frame")

我希望数据框必须在名为 INTENSITY2 的行中将自身限制为大于 10 的值。

我试过这个tf4[, tf4[,"INTENSITY2" > 10, ]],但它不起作用。

【问题讨论】:

  • 这个不一样,刚查了一下页面。
  • 试试看:df[, df["INTENSITY2", ] > 10, FALSE]。与您的代码的唯一区别在于过滤:您打错字并按列值过滤,而不是按行值。
  • 它给出的错误为Error in [.data.frame(tf4, , tf4["INTENSITY2", ] > 10, FALSE) : undefined columns selected
  • 是的!使用整洁的数据要容易得多。我将提供另一个sn-p代码,所以你可以选择=)library(tidyverse); tf4 %>% rownames_to_column("tmp") %>% gather(variable, val, -tmp) %>% spread(tmp, val)

标签: r select row


【解决方案1】:

这也有效。

tf4[,unname(apply(tf4['INTENSITY2',],1,function(x) which(x>10)))]

【讨论】:

  • apply 返回列的名称。 unname 删除它们。 1 表示我们是按行而不是按列(即 2)应用函数。
  • 虽然我已经理解并发现它非常合适,但我想知道为什么使用行比使用列更难。
  • 变量作为列,观察作为行是设置数据框的标准化方法。大多数工作都是为了改进这些操作。但是,在此操作中,我们将行(sd、均值等)视为变量,将列(材料)视为观察值,这不是一个理想的设置。
猜你喜欢
  • 2022-11-29
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
相关资源
最近更新 更多