1

IN R I have a vector of NAME:

[1] "ALKR50SV" "AMKR71SV" "AOKR71SV" "AZKR52SV" "BFKR70SV" "BJKR61SV" "BUKR6HSV" 
    "CDKR61SV" "CFKR31SV"

I want to use them as a name for each new dataframe

Like dataframe of ALKR50SV, dataframe of ALKR50SV ......

for loop like:

NAME[i] <- data1

will cause problem.

What should I do? Thank you.

neilfws
  • 32,751
  • 5
  • 50
  • 63
Young Ge
  • 11
  • 1
  • you want to use these values as dataframe names ? – Mustufain Feb 21 '18 at 21:36
  • 3
    Might be easier to create a named list of dataframes using the vector for the list names. – neilfws Feb 21 '18 at 21:37
  • 4
    This isn't how we do things in R, it will just lead to problems later on. Put the data frames in a single object, a list, and then the list items can have names. e.g. `setNames(my_list_of_dfs, NAME)`. – joran Feb 21 '18 at 21:40

2 Answers2

0

As @joran and @neilfws said, best to work with a list of data.frames. For example, consider the following list of three data.frames

lst <- lapply(1:3, function(x) as.data.frame(matrix(sample(20), ncol = 4)));

You can name list elements

names(lst) <- c("ALKR50SV", "AMKR71SV", "AOKR71SV");

and operate on list elements using lapply, e.g.

lapply(lst, dim);
#$ALKR50SV
#[1] 5 4
#
#$AMKR71SV
#[1] 5 4
#
#$AOKR71SV
#[1] 5 4
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
-1

You can use assign:

numbers <- c('one', 'two', 'three')
for (i in 1:3) {
    assign(nms[i], i)
}
one # 1
two # 2
three # 3

But as others have commented, it is most likely better to put your dataframes into a named list.

C. Braun
  • 5,061
  • 19
  • 47
  • 1
    [Why is using assign a bad idea](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad) – Maurits Evers Feb 22 '18 at 00:01
  • Using assign is a bad idea, but it's not a bad answer to the question. The downvote is not appropriate. – mikeck Feb 22 '18 at 00:11
  • @mikeck I didn't downvote; but I don't agree with your comment. The use of `assign` should not be promoted. Especially not in an answer. – Maurits Evers Feb 22 '18 at 00:31
  • @maurits, I was making a general statement and did not mean to suggest you specifically were the one who downvoted. Perhaps I'm a bit more conservative in using downvotes; it's a technically correct answer that does not break or abuse standard functionality of R, so I don't think it deserves a downvote. But I agree that using `assign` should not be promoted, so I wouldn't upvote it either :) – mikeck Feb 22 '18 at 02:19