refer to vector element in R

94 Views Asked by At

I have a dataframe of survey data, and I want to get relative frequencies from it.

I made a vector of unique genus names from the file:

> CoralGenera <- unique(dfrm$V5)

Then for each element(Genus) in the vector(CoralGenera), I want to run this function:

> mean(dfrm$V5 == "Genus") 

But it's getting each string saved as an element in the vector to be used in the function that is holding me up.

I tried:

> for (Genus in CoralGenera){
   CGrfreq <- c(CGrfreq,mean(dfrm$Genus == Genus))}

Which ran, but returned a vector with more elements than CoralGenera

I've been trying to use lapply() instead to avoid copying, but can't get it to work:

> lapply(seq_along(CoralGenera), mean(dfrm$Genus == Genus))

> lapply(Genus(CoralGenera), mean(dfrm$Genus == "Genus"))

> lapply(CoralGenera, mean(dfrm$Genus == x))

> lapply(CoralGenera, mean(dfrm$Genus == CoralGenera[v]))

Each time it returns an error message like this: Error in match.fun(FUN) : 'mean(dfrm$Genus == Genus)' is not a function, character or symbol

This is my first time writing a code like this in R, so any help will be very much appreciated.

1

There are 1 best solutions below

0
On

It is not clear from what you want the mean. Try one of this:

sapply(CoralGenera, function(genus) mean(dfrm$Genus[dfrm$V5 == genus]))
sapply(CoralGenera, function(genus) mean(dfrm$V5[dfrm$V5 == genus]))