将data.frame转换为data_frame(dplyr)后使用tapply -R

时间:2016-03-04 22:44:51

标签: r dataframe dplyr

我正在使用dplyr和nicheRover包进行一些计算

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)"))

这给出了

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

然后如果我用str()检查它会产生一个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 ...

如何更改上面的tapply命令,以便列像这样的

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试

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)"))

请注意,我直接从niche.plot的示例中取出niche.plot命令。你的行产生了一个单独的,看似无关的错误。

niche.plot似乎在某个时刻做了一些子集,期望向量或奇异值作为输出。 tbl_df虽然与标准data.frames不同,但如果对单个行或列进行子集化,则不会缩减为向量,这似乎会导致问题。在上面的代码中,我刚刚将输出重新转换为标准数据帧。