我无法理解这个R代码有什么问题,我有几行和col有一个测量或NA我基本上想要得到每行中的最小值和最大值看几个cols:
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)
}
答案 0 :(得分:2)
在这一行(和其他三个相似的行)中:
census$min.dbh <- min(trans[1,index.1])
您要将整个列分配给所有相同的值。显然不是你想要的。
也许你想要这样的东西:
census$min.dbh[i] <- min(trans[1,index.1])
请注意,您可以使用apply
执行此类操作。如果您提供示例数据(即,使您的问题成为可重现的示例),那么某人编写一个有效的apply
示例会容易得多。
答案 1 :(得分: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"
。