【问题标题】:How to get rows given multiple values of columns by defining a function in R?如何通过在 R 中定义函数来获取给定多个列值的行?
【发布时间】:2016-08-18 20:34:04
【问题描述】:
    Longitude Latitude     TWC
1      130.5    -16.5     6.935
2      131.5    -16.5    13.912
3      132.5    -16.5    13.244
4      133.5    -16.5    15.556
5      134.5    -16.5    21.380
6      135.5    -16.5    22.267
7      136.5    -16.5    17.398
8      137.5    -16.5    18.570
9      138.5    -16.5 32767.000
10     139.5    -16.5 32767.000
11     140.5    -16.5 32767.000
12     130.5    -16.5    12.854
13     131.5    -16.5    18.449
14     132.5    -16.5    21.339
15     133.5    -16.5    26.097
16     134.5    -16.5    31.306
17     135.5    -16.5    28.225
18     136.5    -16.5    25.373
19     137.5    -16.5    29.772
20     138.5    -16.5 32767.000
21     139.5    -16.5 32767.000
22     140.5    -16.5 32767.000

我有一个这样的数据框(更长),我想获得相同的“经度”和“纬度”值,然后打印这些行。

这段代码对我有帮助

data1 <- data[data$Longitude == '130.5' & data$Latitude =='-16.5',]
  Longitude Latitude    TWC
1      130.5    -16.5  6.935
12     130.5    -16.5 12.854

但我正在寻找一个函数,我可以在其中轻松编写这两个变量(经度、纬度)来获取具有“TWC”值的这些行。

【问题讨论】:

  • 你想要什么作为函数的输入参数?
  • 我猜是长还是宽...?
  • 我输入经度和纬度,函数给出行。
  • @Therru 我发布了一个解决方案。请检查。

标签: r dataframe


【解决方案1】:

我们可以用数据集对象('dat')、相应的列('Lat'、'Long')和要比较的值('valuelat'、'valueLong')编写一个函数)

f1 <- function(dat, Lat, Long, valueLat, valueLong){
          dat[dat[[Lat]]==valueLat & dat[[Long]] == valueLong,]
   }

f1(data, "Latitude", "Longitude",  -16.5, 130.5)
#   Longitude Latitude    TWC
#1      130.5    -16.5  6.935
#12     130.5    -16.5 12.854

如果我们使用相同的数据集,那么我们可以从函数中删除“dat”和列名参数,在函数内部,我们可以将“dat”更改为“data”。

f2 <- function(valueLat, valueLong){
           data[data[["Latitude"]]==valueLat & data[["Longitude"]] == valueLong,]
   }

 f2(-16.5, 130.5)
 #   Longitude Latitude    TWC
 #1      130.5    -16.5  6.935
 #12     130.5    -16.5 12.854

【讨论】:

  • 非常感谢! & 是否可以通过写 f1(130.5, -16.5) 得到这些行?
  • @Therru 是的,在这种情况下,您需要将 'dat' 更改为 'data' 和 'Lat','Long' 更改为 "Latitude", "Longitude"
  • @Therru 在f2 中,我没有在参数中使用data1、“经度”、“纬度”。请检查功能。
猜你喜欢
  • 2015-05-29
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
相关资源
最近更新 更多