0

I need use the same function inside the set of data separated by "ID" for example:

a <- rnorm (12,50,5)
b <- rnorm (12,50,5)
c <- c(1,1,1,2,2,2,3,3,3,4,4,4)
w <- data.frame (cbind(a,b,c))
colnames (w) <- c("X","Y","ID")

resulted as:

      X        Y     ID
1  58.60074 49.50746  1
2  48.58635 41.67082  1
3  52.15529 48.06197  1
4  43.90611 61.65534  2
5  49.98929 57.84950  2
6  43.17375 49.44611  2
7  48.87200 46.63762  3
8  48.70081 54.89588  3
9  48.80352 52.82323  3
10 60.25107 48.05426  4
11 47.90206 55.46229  4
12 41.61667 50.24669  4

set ID = 1, set ID = 2, set ID = 3, set ID = 4. How to aply the same function for each set separately and automatically. Thank you

to Mike: X and Y are the geographical coordinates and I need to use an equation for all rows inside the set together, to get a new coordinate.

to MrFlick: center of points in set ID = 1 example:

x_1 <- mean (w[1:3,1])
y_1 <- mean (w[1:3,2])

resulted as:

> x_1
[1] 53.11413
> y_1
[1] 46.41341

Or in set ID = 2

x_2 <- mean (w[4:6,1])
y_2 <- mean (w[4:6,2])

resulted as:

> x_2
[1] 45.68972
> y_2
[1] 56.31698

to Julian_Hn: it works perfectly. Thank you

ras
  • 1
  • 3
  • what function are you trying to apply? – Mike Mar 26 '19 at 16:47
  • It's easier to help you if your [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) included the desired output so that we can test and verify possible solutions. – MrFlick Mar 26 '19 at 17:11

2 Answers2

1

For the example provided, this gets you what you want:

library(dplyr)

tab <- w %>%
  group_by(ID) %>%
  summarize(mean.x=mean(X), mean.y=mean(Y))

tab

If you're not always looking for the mean, you can substitute other functions in summarize.

phalteman
  • 3,442
  • 1
  • 29
  • 46
0

Split the data.frame by ID and then return the colMeans.

spl <- split.data.frame(w,f=w$ID)
mean_df <- t(sapply(spl,colMeans))
Julian_Hn
  • 2,086
  • 1
  • 8
  • 18