3

Hi I'm trying to return strings that subset all the columns in iris dataset. The output I'm looking for is 'iris$Sepal.Length', 'iris$Sepal.Width', 'iris$Petal.Length', 'iris$Petal.Width', 'iris$Species'.

I tried the following code below, doing a for loop with paste0 function but nothing is returned.

for(i in colnames(iris)){ paste0('iris$',i , collapse ="") } 

How can I solve this?

1
  • 1
    Can you explain a bit more what you're trying to do with the vector of strings? This might be an XY problem and there might be better ways to approach your problem. Commented Mar 20, 2019 at 2:40

2 Answers 2

6

paste0 is vectorized so you can directly do

paste0("iris$", names(iris)) #[1] "iris$Sepal.Length" "iris$Sepal.Width" "iris$Petal.Length" # "iris$Petal.Width" "iris$Species" 

In for loop you need to explicitly tell R to do things

for(i in colnames(iris)){ print(paste0('iris$',i)) } #[1] "iris$Sepal.Length" #[1] "iris$Sepal.Width" #[1] "iris$Petal.Length" #[1] "iris$Petal.Width" #[1] "iris$Species" 

Or you can store it in a character vector

string_name <- character(length = ncol(iris)) for(i in seq_along(names(iris))){ string_name[i] <- paste0('iris$',names(iris)[i]) } string_name #[1] "iris$Sepal.Length" "iris$Sepal.Width" #"iris$Petal.Length" "iris$Petal.Width" "iris$Species" 
Sign up to request clarification or add additional context in comments.

Comments

1

Using your own logic, your code can be corrected as follows:

for( i in 1:length(colnames(iris)) ){ print( paste0('iris$', colnames(iris)[i] , collapse ="") ) } [1] "iris$Sepal.Length" [1] "iris$Sepal.Width" [1] "iris$Petal.Length" [1] "iris$Petal.Width" [1] "iris$Species" 

However @ronak-shah 's solution is mode elegant. I just wanted to show the corrections that could be made to your particular loop.

2 Comments

This is really not a good solution and should definitely not be the accepted answer; if you wanted to know how to correct OPs syntax take a look at @RonakShah's answer. However and more importantly, it would've been critical to point out that paste0 is already vectorised (again, see Ronak's post). SO is about a collection of best coding practises and solutions that (ideally) generalise and apply to other future questions.
@MauritsEvers I agree that this is not an optimal solution. Based on the OP’s code, they appeared to be a beginner and the idea was to guide them through their logic. However in order to keep with best practices, let me know if you think I should delete this answer? Please advise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.