R language-attach, detach, with

Source: Internet
Author: User

In the R language, you can use attach or with when you are working with data in a string column, in order to avoid having to type the object name repeatedly.

1, attach ()

Suppose data.frame contains columns Name,age

Attach (Onedata.frame), you can refer to the elements in the onedata.frame directly, for example:

(1) Create test data frame

> name<-c ("Zhangshan", "Lisi", "Wangwu", "Zhaoliu")
> age<-c (20,30,40,50)
> Onedata.frame<-data.frame (name,age)
> Onedata.frame
Name age
1 Zhangshan 20
2 Lisi 30
3 Wangwu 40
4 Zhaoliu 50

(2) Attach test

> Attach (Onedata.frame)
The following objects is masked _by_. Globalenv:

Age, name

> Age
[1] 20 30 40 50
> Name
[1] "Zhangshan" "Lisi" "Wangwu" "Zhaoliu"
> Detach (Onedata.frame)

> Name
Error: Object ' name ' not found
It is visible that the elements in the access data frame can be searched only between command attach () and detach ().

2. With ()

Using with, like with in JavaScript, is valid in parentheses. For example:

>with (onedata.frame,{

[1] Zhangshan Lisi Wangwu Zhaoliu
Levels:lisi Wangwu Zhangshan Zhaoliu
The problem with using with is that the variables set inside cannot be accessed externally:

> with (Onedata.frame,{name1<-name})
> name1
Error: Object ' name1 ' not found

The solution is to use the <<-assignment notation, for example:

> with (Onedata.frame,{name1<<-name})
> name1
[1] Zhangshan Lisi Wangwu Zhaoliu
Levels:lisi Wangwu Zhangshan Zhaoliu

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

R language-attach, detach, with

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.