0

I wrote a script, that reads CSV-Data with help of user input. For example when the user enters "20 40 160" the CSV files 1, 2 and 3 are read and saved as the data.frames d20, d40 and d160 in my global enviroment/workspace. The variable vel has the values for the user input.

Now for the actual question: Im trying to manipulate the read data in a loop with the vel variable. For example:

for (i in vel) 
{ 
  newVariable"i" <- d"i"[6]

}

I know thats not the correct syntax for the programming, but what im trying to do ist to write a newVariable with a specific row from a specific data frame d. The result should be:

newVariable20 = d20[20]

newVariable40 = d40[20]

newVariable160 = d160[20]

So I think the actual question is, how do I use the Loop Variable for calling out the names of the created data frames and for writing new variables.

s_baldur
  • 29,441
  • 4
  • 36
  • 69
M. Gutier
  • 15
  • 1
  • 5
  • I think this previous question provides a solution: [How to name variables on the fly?](https://stackoverflow.com/questions/2679193/how-to-name-variables-on-the-fly) – Dan Jan 18 '18 at 14:16
  • And also, pay heed to the [first comment](https://stackoverflow.com/questions/2679193/how-to-name-variables-on-the-fly#comment15326407_2679289) in above link's accepted answer. – Parfait Jan 18 '18 at 16:38
  • Thank you both! This made me understand the usefulness of lists and solve my problem – M. Gutier Jan 23 '18 at 12:15

1 Answers1

0

There are a couple of ways to do this. One is to store all of your dataframes in a list originally. There are a couple ways to do this. Start with an empty list and then put each df into the next position in the list. Note that you have to use list(df) because a dataframe is actually already a list and gets messed up if you don't do this.

list_of_df <- list(); 
list_of_df[1] <- list(df1); 
list_of_df["df20"] <- list(df2)

This makes it easy to loop through the dataframes. If you want column 4 of dataframe 2 you just put in

list_of_df[[2]][,4]
# Same thing different code
list_of_df[["df20"]][,4]

The double brackets [[2]] give you the value that is stored in the list at position 2 (instead of [2] which gives you a list containing the value and metadata). The next [,4] says that from the dataframe we just got the value of, we now want to get every row of the 4th column. Note that this will output a vector and not a dataframe.

Or in a loop:

for(df in list_of_df) {
  print(df)
}
Adam Sampson
  • 1,971
  • 1
  • 7
  • 15