探索R中随机数(零)
北京R语言会议纪要

R中将多个变量赋予另外多个变量——一个脑残的方案

Dante posted @ 2014年4月14日 00:33 in R语言 with tags R , 2275 阅读

虽然很难理解为什么有这样的需求,但是我还是遇到过这样的要求:怎么把不同的结果保存到一系列按照某种规则命名的变量中。而且是不止一次遇到这种需求。

我觉得通过合理地安排编程逻辑,应该可以避免,但是无法避免的时候,还是有别的方法的:在R中,实用assign(x, value)语句。这样可以创建一个名为x(注意到x是一个字符串)的变量,并将value对应的值赋予它。

不过今天师妹给我带来了新的挑战(师妹真的是人类进步的动力啊!):如果需要将当前环境中名为a0~a9的变量中的一部分赋值给b0~b9的变量,那么,即使用assign也有一点难度。因为当师妹用如下代码的时候:

for(i in 0:9) {
    vname <- paste("a", i, sep="")
    assign(paste("b", i, sep=""), value=vname)
}

得到的结果是b1="a1"这样的结果,也就是说,我们把一个字符串赋值给b1了!

我给出的方法是用environment():

vars <- environment()
for(i in 0:9) {
    vname <- paste("a", i, sep="")
    assign(paste("b", i, sep=""), value=vars[[vname]])
}

嗯,任务完成!准备让师妹请我吃顿饭。

当然,在我敲下上面这句话的时候,我觉得,这种做法挺脑残的。首先这不是一种好的代码风格,然后,其实把a1~a9放在一个列表里面不就结了吗?

不过,还是很开心,因为估计能够坑来一顿饭,而且让我可以写一篇博客。

Avatar_small
TomHall 说:
2014年4月14日 02:28

为啥不先paste起来,然后eval?

Avatar_small
Dante 说:
2014年4月14日 06:14

@TomHall: eval("t1<-t2", env)只是得到一个字符串而已。或者有别的方法将字符串转换成expression?

Avatar_small
V 说:
2014年4月30日 00:26

@Dante: 迟到请客没?:)

Avatar_small
TomHall 说:
2014年4月30日 00:29

@Dante: 好像忘记回复了…… 你试试eval(parse(text="5+5"))

Avatar_small
V 说:
2014年4月30日 00:29

吃到请客没?:)怎么删掉上一条?

Avatar_small
Dante 说:
2014年4月30日 01:32

@TomHall: 还是一个字符串。好像R里面的expression挺有意思的。我去看看手册回来再写一写好了。

Avatar_small
TomHall 说:
2014年4月30日 02:05

@Dante: 你确定??我们用的是同一个R么……

> eval(parse(text="5+5"))
[1] 10

Avatar_small
Dante 说:
2014年4月30日 12:36

@TomHall: 我测试的R版本是3.0.1

Avatar_small
TomHall 说:
2014年4月30日 16:47

@Dante: 太奇怪了。http://stackoverflow.com/questions/1743698/r-eval-expression

Avatar_small
Dante 说:
2014年4月30日 17:36

@TomHall: 太囧了,我把parse看成了paste了。。。

Avatar_small
TomHall 说:
2014年4月30日 20:07

@Dante: 我觉得我这个办法比你用到的更好

Avatar_small
Dante 说:
2014年5月02日 02:27

@TomHall: 确实,不用依赖于环境。

Avatar_small
Ken 说:
2014年5月30日 04:34

貌似不用这么麻烦,直接用get()即可。

# 随便产生一点数据

for(i in 0:9) {
assign(paste0("a",i),i)
}

# 用 get 获取给定字符串名称变量的值
for(i in 0:9) {
assign(paste0("b",i),get(paste0("a",i)))
}

Avatar_small
Dante 说:
2014年5月30日 07:06

@Ken: 受教了,谢谢!

Avatar_small
NCERT Term 2 Sample 说:
2022年9月16日 04:05

Session 2 of the Course is called Term 2, and the Class 2nd Standard students who prepared for their examination tests can download the NCERT 2nd Term Question Paper 2023 Pdf with Answers for all Languages and Subjects of the Course. Every Central Board and other Schools have conducted their examination tests as per the revised syllabus and curriculum designed and published by NCERT.NCERT Term 2 Sample Paper Class 2 Every year the NCERT has published the study and learning material for every 2nd class student studying at all locations of the country for both SA-2, FA3, FA-4 and Assignment exams to Hindi mediu.

Avatar_small
SEO 说:
2023年12月03日 20:22

안전놀이터 추천 is crucial, and Toto Match delivers. Their emphasis on security and fairness sets them apart in the industry.

Avatar_small
civaget 说:
2023年12月04日 06:35

Adaptability is vital in the world of 구글 상위노출. Stay flexible and adjust your strategies to the ever-changing SEO landscape.

Avatar_small
civaget 说:
2023年12月08日 23:07

오피스타's extensive coverage ensures I never miss an exciting OP spot in my area.

Avatar_small
civaget 说:
2023年12月09日 01:38

Trust op사이트 순위 for reliable website recommendations.

Avatar_small
civaget 说:
2023年12月09日 02:01

Discover nightlife hotspots with 오피가이드's vibrant user community.

Avatar_small
civaget 说:
2023年12月09日 02:08

에볼루션카지노 exceeds expectations with its live games. The professional dealers and high-quality streaming make it a top choice for casino enthusiasts.

Avatar_small
civaget 说:
2023年12月10日 01:55

The wealth of information on 오피 sites never ceases to amaze me.

Avatar_small
civaget 说:
2023年12月11日 20:46

After a long day of exploring, 제주안마 was exactly what I needed. It's the best way to unwind and recharge on Jeju Island.

Avatar_small
civaget 说:
2023年12月11日 21:03

부산오피 in Haeundae is a unique experience. The coastal elegance and Officetel culture blend seamlessly.

Avatar_small
civaget 说:
2023年12月14日 05:28

Of course, things are balanced out by some great characterisation work and developing relationships and the movie does well to mix the drama and development in amongst the spectacle but it still feels as if perhaps it could have added a little bit more to reinforce the scale of things and to impress on a simplistically entertaining level. 축구중계

Avatar_small
civaget 说:
2023年12月15日 22:39

안전카지노's recognition in the industry speaks volumes about its trustworthiness.

Avatar_small
civaget 说:
2023年12月15日 22:49

Oga's 출장마사지 is a hidden gem. The therapists are fantastic, and it's the best way to unwind.

Avatar_small
civaget 说:
2023年12月16日 03:45

Discover hidden gems for relaxation with 오피뷰. A treasure trove of tranquility!

Avatar_small
civaget 说:
2023年12月17日 04:33

스포츠중계 offers an endless supply of sports content.

Avatar_small
civaget 说:
2023年12月19日 22:29

Woh Everyone loves you , bookmarked ! My partner and i take issue in your last point. 에볼루션카지노

Avatar_small
civaget 说:
2023年12月20日 01:29

Officetel exploration made seamless by 오피가이드. Trust their real-time updates and advanced search features for an unmatched officetel experience.

Avatar_small
civaget 说:
2023年12月31日 20:02

The popularity scoring on 티비위키 is incredibly useful.

Avatar_small
civaget 说:
2024年1月02日 22:04

안전카지노 never disappoints – it's the best!

Avatar_small
civaget 说:
2024年1月07日 01:32

천안오피 is my go-to for relaxation. Their Aromatherapy Massage is heavenly, and the location is convenient.

Avatar_small
civaget 说:
2024年1月11日 00:47

Relax and unwind at 인천출장마사지 – a haven of tranquility in Incheon.

Avatar_small
SEO 说:
2024年1月22日 22:00

I have been reading out some of your articles and i must say nice stuff. I will definitely bookmark your blog. The Presidential Family

Avatar_small
SEO 说:
2024年1月31日 18:29

Sweet site, super pattern , real clean and utilize genial . lpb piso wifi 10.0.0.1 pause time login

Avatar_small
how to turn off do n 说:
2024年2月02日 17:49

Wholesale Cheap Handbags Will you be ok merely repost this on my site? I’ve to allow credit where it can be due. Have got a great day!

Avatar_small
SEO 说:
2024年2月03日 20:15

I would like to consider the ability of thanking you for the professional advice I have often enjoyed going to your site. I will be looking forward to the actual commencement of my college research and the general prep would never have been complete without coming to your website. If I could be of any help to others, I would be glad to help by means of what I have gained from here. Kosova Airlines Büyükçekmece Escort

Avatar_small
ads2 说:
2024年2月04日 17:51

Needed to compose you a tiny note to finally thank you very much yet again for your personal splendid methods you have discussed above. It is strangely open-handed with people like you to provide publicly all that a number of people would have marketed as an electronic book to generate some bucks for their own end, primarily now that you could possibly have tried it if you ever wanted. These inspiring ideas likewise acted like a fantastic way to know that the rest have the same dreams really like my personal own to see a whole lot more concerning this problem. I'm sure there are thousands of more enjoyable times in the future for many who check out your blog. 1xbet free bet promo code

Avatar_small
seo 说:
2024年2月06日 20:09

If you’re still on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which one sounds better to you, and which interface makes you smile more. Then you’ll know which is right for you. agen murahqq

Avatar_small
seo 说:
2024年2月10日 17:37

This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your great post. Also, I have shared your site in my social networks! 셔츠룸

Avatar_small
ads2 说:
2024年2月11日 18:51

House Lawyers… [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]… <a href="https://betterpurchass.com/what-is-svm-mode-in-your-bios/">SVM Mode</a>

Avatar_small
seo 说:
2024年2月11日 23:05

I dont think Ive scan anything like this before. So good to find somebody with some original thoughts on this subject. nice one for starting this up. This site is something that is needed on the web, someone with a little originality. Good job for bringing something new to the internet! Blox Fruits codes

Avatar_small
seo 说:
2024年2月12日 00:15

Conveyancing Solicitors… [...]below you’ll find the link to some sites that we think you should visit[...]… What is the price of aluminum strip

Avatar_small
seo 说:
2024年2月12日 01:51

Howdy! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations? Basicstero.ws

Avatar_small
ads2 说:
2024年2月17日 18:26

I’m impressed, I must say. Actually rarely do you encounter a blog that’s both educative and entertaining, and let me tell you, you’ve got hit the nail to the head. Your notion is outstanding; the issue is an issue that not enough people are speaking intelligently about. I am very happy that we found this at my look for something about it.

Avatar_small
ads2 说:
2024年2月17日 22:55

I really like your article. It’s evident that you have a lot knowledge on this topic. Your points are well made and relatable. Thanks for writing engaging and interesting material. methatreams

Avatar_small
ads2 说:
2024年2月21日 23:45

This is a excellent blog, would you be involved in doing an interview about just how you designed it? If so e-mail me! NBA Players That Are Jehovah Witnesses

Avatar_small
ads2 说:
2024年2月25日 00:24

There is numerous separate years Los angeles Weight reduction eating plan with each a person is a necessity. The pioneer part can be your original getting rid of belonging to the extra pounds. la weight loss Do Alec and Kaleb get paid for commercials

Avatar_small
gggg 说:
2024年2月26日 01:28

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Methatreams

Avatar_small
gggg 说:
2024年2月28日 00:45

Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also Marius Blomlie Reset

Avatar_small
gggg 说:
2024年2月28日 00:59

A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. How2Invest

Avatar_small
gggg 说:
2024年3月18日 01:14

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. Elva Guerra Age


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter