通过R中的数据帧进行基本循环计算

时间:2013-08-16 19:26:13

标签: r loops for-loop

我有这个结构:

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

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

2 个答案:

答案 0 :(得分:0)

2件事:

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

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

答案 1 :(得分: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)