Therru - 1 year ago 64
R Question

# How to get rows given multiple values of columns by defining a function in R?

``````    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
``````

I have a dataframe like this (much more longer) and I want to get the same "Longitude" and "Latitude" values and then print these rows.

This code helps me

``````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
``````

but I am looking for a function where I can easily write these two variables(Longitude,Latitude) to get these rows with "TWC" value.

We can write a function with the dataset object ('dat'), the respective columns ('Lat', 'Long') and the values to be compared ('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
``````

If we are using the same dataset, then we can remove the 'dat' and column name arguments from the function and inside the function, we can change 'dat' to '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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download