0

我有这个结构:

census <- structure(list(date1 = c(1993L, 1993L, 1993L), dbh1 = c(NA, 40.7, 
67), liana1 = c(NA, 2, 3), date2 = c(1994L, 1994L, 1994L), dbh2 =
c(NA, 
41.3, NA), date3 = c(1995L, 1995L, 1995L), dbh3 = c(NA_real_,  NA_real_, NA_real_), date4 = c(1996L, 1996L, 1996L), dbh4 =
c(NA_real_,  NA_real_, NA_real_), date5 = c(1998L, 1998L, 1998L), dbh5
= c(NA_real_,  NA_real_, NA_real_), date6 = c(2000L, 2000L, 2000L), dbh6 = c(NA_real_,  NA_real_, NA_real_), date7 = c(2003L, 2003L,
2003L), dbh7 = c(NA_real_,  NA_real_, NA_real_), liana7 = c(NA_real_,
NA_real_, NA_real_), 
    date8 = c(2006L, 2006L, 2006L), dbh8 = c(20.1, NA, NA), date9 = c(2009L, 
     2009L, 2009L), dbh9 = c(24.2, NA, NA), liana9 = structure(c(4L, 
     1L, 1L), .Label = c("", ",", "+", "1", "2", "3"), class = "factor"), 
     death = c(NA, 1995L, 1994L), wd = c(0.6185, 0.6185, 0.6185
     )), .Names = c("date1", "dbh1", "liana1", "date2", "dbh2",  "date3", "dbh3", "date4", "dbh4", "date5", "dbh5", "date6", "dbh6", 
 "date7", "dbh7", "liana7", "date8", "dbh8", "date9", "dbh9", 
 "liana9", "death", "wd"), row.names = c(NA, 3L), class = "data.frame")

我想获取每个“dbh”(1 到 9)列并应用这些值的方程。然后我试图将这些结果添加到我的数据框中的新列中(添加新的 9 列)。为此,我想出了这个循环:

 dbh =c("dbh1","dbh2","dbh3","dbh4","dbh5","dbh6","dbh7","dbh8","dbh9")



for (i in 1:9) {
     census[,31+i] <- census$wd * exp(-1.499 + 2.148 * log(census$dbh[i]) +
     0.207*(log(census$dbh[i]))^2 - 0.0281*(log(census$dbh[i]))^3) / 1000                                 
 }

我开始学习如何循环,所以我什至不确定这是否可行,但我得到的错误是:

Error in log(census$dbh[i]) :    non-numeric argument to mathematical
function

任何想法如何解决这一问题?提前致谢!

4

2 回答 2

0

2件事:

1)您需要在计算中将 census$dbh[i] 替换为 census[dbh[i]] 。我不完全理解为什么这很重要,但确实如此。

2) 之后,您应该检查结果的去向。在您的示例中,它们转到第 32-40 列,但 data.frame 中只有 23 列,因此 R 给出错误,因为它不喜欢这将创建的空白列。对于示例,您需要 census[,23+i] 才能使 for 循环的结果起作用。

于 2013-08-16T19:58:49.980 回答
0

改用这个:

l <- log(census[,grepl("^dbh",names(census))])
Result <- census$wd * exp(-1.499 + 2.148*l + 0.207*l^2 - 0.0281*l^3) / 1000

结果:

      dbh1    dbh2 dbh3 dbh4 dbh5 dbh6 dbh7      dbh8      dbh9
1       NA      NA   NA   NA   NA   NA   NA 0.2626273 0.4272698
2 1.626766 1.68795   NA   NA   NA   NA   NA        NA        NA
3 5.558074      NA   NA   NA   NA   NA   NA        NA        NA

如果要将其添加到原始数据框中,请使用:

names(Result) <- paste("transformed", names(Result))
cbind(census, Result)
于 2013-08-16T20:17:58.450 回答