我有以下代码:
canada <- c(50, 50, 50)
korea <- c(70, 70, 70)
brazil <- c(100, 100, 100)
fruit <- rbind(canada, korea, brazil)
colnames(fruit) <- c("apple", "orange", "banana")我想让它看起来像这样
There are 50 thousand farms in Canada.这就是我试过的:
one <- function(x){
x <- tolower(x) # assuming all row names are in lower case
myrow <- fruit[x,]
country <- paste0(tools::toTitleCase(x))
count <- sapply(seq_along(myrow),
function(x, n, i){paste0(x)},
x=myrow[1], n=names(myrow))
count[length(count)] <- paste0(count[length(count)])
count <- paste0(count[1])
cat("There are", count, "thousand farms in", country, ".")
}
cat(one("canada"))但是,我得到的是:
There are 50 thousand farms in Canada .我需要保留我在这里演示的代码。到目前为止,我尝试了粘贴函数,但我知道paste0应该是我最后用来清除空间的工具。你的帮助将不胜感激。
发布于 2017-08-20 16:44:31
在字符串部件上使用paste0而不是计数。手动写你需要的空格。就像这样:
one <- function(x){
x <- tolower(x) # assuming all row names are in lower case
myrow <- fruit[x,]
country <- paste0(tools::toTitleCase(x))
count <- sapply(seq_along(myrow),
function(x, n, i){paste0(x)},
x=myrow[1], n=names(myrow))
count[length(count)] <- paste0(count[length(count)])
count <- count[1]
cat(paste0("There are ", count, " thousand farms in ", country, "."))
}
one("canada")发布于 2017-08-20 16:47:28
我不是一个r程序员,所以我不太懂语法。但是在Python中,这可以按以下方式修复
one <- function(x){
x <- tolower(x) # assuming all row names are in lower case
myrow <- fruit[x,]
country <- paste0(tools::toTitleCase(x))
count <- sapply(seq_along(myrow),
function(x, n, i){paste0(x)},
x=myrow[1], n=names(myrow))
count[length(count)] <- paste0(count[length(count)])
count <- paste0(count[1])
cat("There are "+ str(count) " thousand farms in "+ country + ".")
}
cat(one("canada"))我在这里试图做的是,而不是,,而是使用连接,即+和str(count)将count的整数值更改为字符串值。
发布于 2017-08-20 16:59:04
也许我完全离开了,但是下面的内容也是一样的,而且要简单得多。
one <- function(x){
x <- tolower(x) # assuming all row names are in lower case
count <- fruit[x, 1]
country <- paste0(tools::toTitleCase(x))
cat(paste0("There are ", count, " thousand farms in ", country, ".\n"))
}
one("canada")
There are 50 thousand farms in Canada.
one("korea")
There are 70 thousand farms in Korea.
one("brazil")
There are 100 thousand farms in Brazil.如果我不明白,请原谅噪音。
https://stackoverflow.com/questions/45784428
复制相似问题