Leosar
Leosar

Reputation: 2072

Using tapply after convert a data.frame to a data_frame (dplyr) - R

I am using the dplyr and nicheRover packages to do some calculations

require(nicheROVER)
data(fish)

require(dplyr)

fish <- fish %>% group_by(species)

# other things I do with dplyr

clrs <- c("black", "red", "blue", "orange")  # colors for each species

fish.par <- tapply(1:nrow(fish), fish$species, function(ii) niw.post(nsamples = 10, 
                                                                     X = fish[ii, 2:4]))

# format data for plotting function

fish.data <- tapply(1:nrow(fish), fish$species, function(ii) X = fish[ii, 2:4])

niche.plot(niche.par = fish.par, niche.data = fish.data, pfrac = 0.05,  
           col = clrs, xlab = expression("Isotope Ratio (per mil)"))

This gives

Error in density.default(niche.data[[ii]][, ci], n = ndens) : 
  argument 'x' must be numeric

Then if I check with str() it results in a tbl_df

str(fish.data[[1]][,1]) 

Classes ‘tbl_df’ and 'data.frame':  69 obs. of  1 variable:  $ D15N: num  12.2 11.2 12.1 11.2 12.1 ...

how can I change the tapply command above so that the columns are num like this

str(fish.data[[1]][,1])

num [1:69] 12.2 11.2 12.1 11.2 12.1 ...

Thanks!

Upvotes: 0

Views: 127

Answers (1)

coffeinjunky
coffeinjunky

Reputation: 11514

Try

fish.data <- tapply(1:nrow(fish), fish$species, 
             function(ii) X = as.data.frame(fish[ii, 2:4]))

niche.plot(niche.par = fish.par, niche.data = fish.data, pfrac = .1,
           iso.names = expression(delta^{15}*N, delta^{13}*C, delta^{34}*S),
           col = clrs, xlab = expression("Isotope Ratio (\u2030)"))

Note that I took the niche.plot command straight out of the examples of niche.plot. Your line produced a separate and seemingly unrelated error.

It seems that niche.plot is doing some subsetting at some point, expecting a vector or singular value as output. tbl_df's do not reduce to vectors if subsetting a single row or column though, unlike standard data.frames, and this seems to cause the problem. In the above code, I have just reconverted the output into a standard dataframe.

Upvotes: 1

Related Questions