0

我无法理解这个 R 代码有什么问题,我有几行和一个带有测量值或 NA 的列,我基本上想在每行中查看几个列中的最小值和最大值:

require(plyr)

census <- read.csv("sps_census.csv")
info <- read.csv("sps_info.csv")


for (i in 1: nrow(census)) {
  trans <- census[i,c("dbh1","dbh2","dbh3","dbh4","dbh5","dbh6","dbh7","dbh8", "dbh9")]
  index.1 <- which (trans != "NA") #some NAs are in the data
  census$min.dbh <- min(trans[1,index.1])
  census$min.dbh.index <- min(index.1)
  census$max.dbh <- max(trans[1,index.1])
  census$max.dbh.index  <- max(index.1)
}
4

2 回答 2

2

在这一行(以及其他三个类似的行):

census$min.dbh <- min(trans[1,index.1])

您正在将一整列分配给所有相同的值。显然不是你想要的。

也许你想要这样的东西:

census$min.dbh[i] <- min(trans[1,index.1])

请注意,您可以使用它apply来执行此类操作。apply如果您提供示例数据(即,使您的问题成为可重复的示例),那么某人编写一个工作示例会容易得多。

于 2013-03-23T19:56:59.470 回答
0

您可以使用apply

index <- c"dbh1","dbh2","dbh3","dbh4","dbh5","dbh6","dbh7","dbh8", "dbh9") #or paste("dbh",1:9,sep="")

census$min.dbh <- apply(census[index], 1, min, na.rm=T)
census$min.db.index <- apply(census[index], 1, function(x){ min(which(!is.na(x))) })
census$max.dbh <- apply(census[index], 1, max, na.rm=T)
census$max.db.index <- apply(census[index], 1, function(x){ max(which(!is.na(x))) })

请注意,我使用is.na(x)的是x != "NA".

于 2013-03-23T21:42:58.170 回答