如何在R中使用tapply()来使用aritmatic

时间:2016-03-03 14:04:50

标签: r

我从csv文件中调用高度,直径和年龄。我试图用pi x h x r ^ 2来计算树的体积。为了计算半径,我将dbh除以2.然后我得到了这个错误。

  

dbh / 2中的错误:二元运算符的非数字参数

a-tag

在向量dbh中,它根据森林(即ID)存储来自他csv文件的直径。

如何将dbh除以2,同时仍然保留每个值的格式,由其接收ID(即森林---> treeg $ forest)存储,treeg是调用csv文件的数据帧。 / p>

setwd("/Users/user/Desktop/")
treeg <- read.csv("treeg.csv",row.names=1)
head(treeg)

heights <- tapply(treeg$height.ft,treeg$forest, identity) 
ages    <- tapply(treeg$age,treeg$forest, identity)
dbh     <- tapply(treeg$dbh.in,treeg$forest, identity) 

radius  <- dbh / 2

1 个答案:

答案 0 :(得分:2)

您是否只是想创建一个dbh.in除以2的半径列?

treeg <- read.table(textConnection("tree.ID forest habitat dbh.in height.ft age
1       1      4       5   14.6      71.4  55
2       1      4       5   12.4      61.4  45
3       1      4       5    8.8      40.1  35
4       1      4       5    7.0      28.6  25
5       1      4       5    4.0      19.6  15
6       2      4       5   20.0     103.4 107"), header=TRUE)

treeg$radius <- treeg$dbh.in / 2

或者你需要那个dbh列表...

dbh     <- tapply(treeg$dbh.in,treeg$forest, identity) 
> dbh
$`4`
[1] 14.6 12.4  8.8  7.0  4.0 20.0 

lapply(dbh, function(x)x/2)
List of 1
$ 4: num [1:6] 7.3 6.2 4.4 3.5 2 10