Reputation: 1111
I have the following code:
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")
I want it to look like this:
There are 50 thousand farms in Canada.
This is what I tried:
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"))
But, this is what I get:
There are 50 thousand farms in Canada .
I need to keep the code I've demonstrated here. So far, I tried the paste function, but I know that paste0 should be what I am using for getting rid of the space at the end. Your help would be much appreciated.
Upvotes: 0
Views: 154
Reputation: 76450
Maybe I'm completely off, but the following does the same and is much simpler.
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.
If I didn't understand it, please excuse the noise.
Upvotes: 0
Reputation: 53
I am not an r programmer so I don't know the syntax that well. But in Python this could be fixed as followed
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"))
What I am trying to do here is instead of ,
I use concatenation that is +
and str(count)
to change integer value of count
to a string value.
Upvotes: 0
Reputation: 1614
use paste0
on string parts instead of counts. and write spaces you need manually.
like this:
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")
Upvotes: 1