Reputation: 4317
This should be an easy question for someone out there...
I have a data frame that looks like this:
df1
longitude lattitude 10000 5 1.5 1.4 1.3 1.2 1 0.5 0.1 0.001
0 -119.8304 34.44190 107 14 8 8 8 8 7 5 5 1
1 -119.6768 34.41962 107 19 5 5 5 5 5 3 2 1
2 -119.7162 34.41911 107 25 9 8 8 5 4 1 1 1
3 -119.7439 34.44017 107 22 7 7 6 5 5 2 1 1
Which was created by this code:
library(geosphere)
df1 <- data.frame(longitude=c(-119.8304, -119.6768, -119.7162, -119.7439, -120.4406, -119.5296, -120.4198, -119.8221, -119.7269, -120.4252, -120.4573, -120.4581),
lattitude=c(34.44, 34.42, 34.42, 34.44, 34.64, 34.41, 34.94, 34.44, 34.44, 34.97, 34.65, 34.65))
boundary <- c(10000, 5, 1.5, 1.4, 1.3, 1.2, 1, 0.5, 0.1, 0.001)
names(boundary) <- boundary
df1 <- cbind(df1, lapply(boundary, function(x) rowSums(distm(df1, fun = distHaversine) / 1000 <= x)))
But I need the values in the data frame df1
to be manipulated such that the value in all the columns except latitude
and longitude
will get divided by pi*x^2
(pi times x squared). Can I use lapply in this case?
The output should be like:
df1
longitude lattitude 10000 5 1.5 1.4 1.3 1.2 1 0.5 0.1 0.001
0 -119.8304 34.44190 0 0.177 1.12 1.29 etc...
Upvotes: 3
Views: 65
Reputation: 887108
We can use setdiff
to get the names of the dataset except the 'longitude', 'lattitude' column. Then loop through the subset of columns, do the calculation, and update the dataset
j1 <- setdiff(names(df1), c("longitude", "lattitude"))
df1[j1] <- lapply(df1[j1], function(x) x/(pi*x^2))
Or we can use tidyverse
library(dplyr)
df1 %>%
mutate_at(vars(-matches("longitude", "lattitude")), funs(./(pi*.^2)))
Upvotes: 2