r - 如何打印包含列的特定值的行?

标签 r for-loop if-statement

我试图创建一个循环并搜索一列中的值,然后显示该值所在的所有第一行,我想从 1950 年到 2016 年

Em=
 year    x      y
 1950    5      3
 1950    4      3
 1950    2      4
 1950    1      5
 1951    6      7
 1951    5      6
 1951    1      4
 1951    0      3

我一直在尝试这个:

for (p in 1:nrow(Em)){
if (Em[p,"year"]==1950)
   break
   print(Em[p,])} #it is not showing me just the first row that matches
{ else if (Em[p,"year"]==1951)
    break
    print(Em[p,])}

并获取

year    x      y
1950    5      3
1951    6      7

最佳答案

使用 Base R 的解决方案:

Em_sub = aggregate(. ~ year, data = Em, '[', 1)

或使用dplyr:

library(dplyr)
Em_sub = Em %>%
  group_by(year) %>%
  slice(1)

结果:

  year x y
1 1950 5 3
2 1951 6 7

# A tibble: 2 x 3
# Groups:   year [2]
   year     x     y
  <int> <int> <int>
1  1950     5     3
2  1951     6     7

数据:

Em = read.table(text = "year    x      y
                1950    5      3
                1950    4      3
                1950    2      4
                1950    1      5
                1951    6      7
                1951    5      6
                1951    1      4
                1951    0      3", header = TRUE)

关于r - 如何打印包含列的特定值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059978/

相关文章:

r - 在Rastervis中使用gplot方法时如何去除背景灰色?

javascript - 如何在react状态钩子(Hook)上使用map函数

PHP:检查数据库中的项目是否具有相同的名称

php - 使用 PHP 的 "for"。使用特定数字代替序列号

javascript - JS - console.log(..) 在 for 循环内的回调函数之后输出

c - 以下两种情况在性能上有什么区别吗?

regex - R删除重复的数字序列

r - 在 R 中,如何制作一个六条形图,其中每个条形包含一系列数据?

r - 通过 .rmd 或 Shiny 在本地 .html 上进行交互式绘图

for-loop - 为什么闭包中允许使用 'for .. in'?