Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

r - Assign data frame name to list elements using name vector

I have a data frame, 'mydata':

head(mydata)

ID      MDC
000001  21A
000002  5
000003  8
...

I've split my data frame by one of it's column values, namely 'MDC'. This created a list, subdivided into further lists by the column value 'MDC':

mylist <- split(mydata, mydata$MDC, drop=TRUE)
summary(mylist)

    Length Class      Mode
0   75     data.frame list
1   75     data.frame list
10  75     data.frame list
11  75     data.frame list
12  75     data.frame list
21A 75     data.frame list
...

I now want to create a data frame for each MDC with the corresponding name, e.g. 'MDC1'. How can I assign the MDC values to the list elements?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems like this should work

MDC <- paste0("MDC", sort(unique(mydata$MDC)))
names(mylist) <- MDC
list2env(mylist, .GlobalEnv)
ls() # Checking environment
## [1] "MDC"    "MDC21A" "MDC5"   "MDC8"   "mydata" "mylist"

Edit: Per @flodel's comment- In case you want to make further operations on these data frames, you shouldn't copy them into the global environment. You should leave them in mylist and do all your operation on that list using functions such as lapply and rapply


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...