1
votes

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?

2
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.Maurits Evers

2 Answers

5
votes

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"   
0
votes

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.