I'm very new to R. I have a dataframe with 100 fields each consisting of 65 species of plants (6500 rows). I want to calculate a value for each of the 100 fields, which should be:
value (field_1) = (plant_cover1 * plant_trait1 + plant_cover2 * plant_trait2 + ......)/(plant_cover1 + plant_cover2 + .....)
Plant_cover1: Vertical_density value for species 1 Plant_trait1: slamean value for species 1
I've tried the following, but I'm stuck. Also i get the error "the condition has length > 1 and only the first element will be used".
for(i in levels(NPT$Feltnummer)) {
for (i in levels(NPT$Artsnavn_dansk)) {
if(NPT$Vertikal_densitet>0 & NPT$slamean>0) {
return((NPT$vertikal_densitet*NPT$slamean)/NPT$Vertikal_densitet)
}sum()}Return()}
How would I go about calculating the 100 values? I hope you can help.
Here's some of my data (2 fields):
dput(head(NPT, 130))
structure(list(Feltnummer = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Vertikal_densitet = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.64, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.24,
0.48, 0, 0, 0, 0, 0.36, 0.44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0.64, 0.64, 0, 0, 0, 0, 0.04, 0.84, 0, 0, 0, 0.32,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), slamean = c(54.015,
0, 29.3766666666667, 0, 0, 0, 29.5933333333333, 20.63, 0, 0,
36.33, 19.8166666666667, 0, 0, 16.4233333333333, 5.95, 9.35,
27, 12.82, 39.27, 31.6425, 15.3433333333333, 0, 20.4775, 11.37,
22.8, 28.185, 0, 0, 12.41, 4.92, 18.99, 41.47, 32.05, 0, 19.1875,
0, 7.61, 0, 0, 0, 15.0425, 0, 15.586, 0, 0, 8.425, 34.0825, 0,
13.71, 13.55, 0, 24.87, 0, 17.97, 13.96, 18.85, 0, 0, 29.13,
12.87, 10.11, 30.11, 0, 0, 54.015, 0, 29.3766666666667, 0, 0,
0, 29.5933333333333, 20.63, 0, 0, 36.33, 19.8166666666667, 0,
0, 16.4233333333333, 5.95, 9.35, 27, 12.82, 39.27, 31.6425, 15.3433333333333,
0, 20.4775, 11.37, 22.8, 28.185, 0, 0, 12.41, 4.92, 18.99, 41.47,
32.05, 0, 19.1875, 0, 7.61, 0, 0, 0, 15.0425, 0, 15.586, 0, 0,
8.425, 34.0825, 0, 13.71, 13.55, 0, 24.87, 0, 17.97, 13.96, 18.85,
0, 0, 29.13, 12.87, 10.11, 30.11, 0, 0)), row.names = c(NA, -130L
), class = c("tbl_df", "tbl", "data.frame"))
str(NPT)
tibble [6,500 x 3] (S3: tbl_df/tbl/data.frame)
$ Feltnummer : num [1:6500] 1 1 1 1 1 1 1 1 1 1 ...
$ Vertikal_densitet: num [1:6500] 0 0 0 0 0 0 0 0 0 0 ...
$ slamean : num [1:6500] 54 0 29.4 0 0 ...