我在韩国有以下数据,两列之间缺少值:
canada <- c(100, 0, 100)
korea <- c(100, "", 100)
brazil <- c(100, 90, 100)
fruit <- rbind(canada, korea, brazil)
colnames(fruit) <- c("apple", "orange", "banana")
fruit
我需要将水果的名称从最小值打印到最大值。我有这个:
price <- function(val){
# General Functions ----
val <- tolower(val)
myrow <- fruit[val,]
nation <- tools::toTitleCase(val)
name.min <- names(myrow)[which.min(c(myrow))]
name.max <- names(myrow)[which.max(c(myrow))]
cat(paste0("There is an 'NA' between two columns: ", name.min, " ", name.max))
}
问题在于,因为韩国的苹果和香蕉之间缺少价值,所以这就是它的印刷品:
> price("korea")
There is an NA between two columns: apple apple
我希望它看起来像这样:
> price("korea")
There is an NA between two columns? No problem: apple banana
答案 0 :(得分:1)
这很难看但应该做你想要的事情:
price <- function(x) {
temp <- data.frame(val = as.numeric(fruit[rownames(fruit)==x,]),
name = colnames(fruit))
ind <- which(is.na(temp[,1]))
if (length(ind!=0)) temp <- temp[-ind,]
temp[order(temp[,1]),2]
}
price("korea")
答案 1 :(得分:0)
price <- function(val){
val <- tolower(val)
myrow <- fruit[val,]
nation <- tools::toTitleCase(val)
name.min <- names(myrow)[which.min(c(myrow))]
name.max <- names(which(myrow == max(myrow)))
cat(paste0(name.max))
}
> price("korea")
apple banana