[R] add one variable to a data frame

Ding, Yuan Chun ycd|ng @end|ng |rom coh@org
Sat May 12 00:22:18 CEST 2018


Hi Bert,

Thank you very much for your beautiful input!!

I think I understand your concern regarding creating a unnecessary column.     Each duplicated rows in order represents a chromosome region containing two to ten adjacent loci.  When we present data, we want to show region1, region2, …;  I will make scatter plots for each region by selection of top loci based on  p value and effect size.  So I like to define a simple region tag or label using integer.  Anyway, there are a lot of more columns in the data frame.

Thanks again for this useful r-help platform.  I posted my question and then got answer after coming back from lunch.  I am a beginner in R, so question might be trivial.

Ding

From: Bert Gunter [mailto:bgunter.4567 using gmail.com]
Sent: Friday, May 11, 2018 1:37 PM
To: Sarah Goslee
Cc: Ding, Yuan Chun; r-help mailing list
Subject: Re: [R] add one variable to a data frame

________________________________
[Attention: This email came from an external source. Do not open attachments or click on links from unknown senders or unexpected emails.]
________________________________

Sarah et. al.:
As a matter of aesthetics (i.e. my personal ocd-ness) I prefer using the public API of an object, i.e. *not* to makes use of the representation of a factor as essentially an integer vector with labels, but rather to use its documented behavior. (Feel free to ignore this remark!)
Anyway,

>cumsum(!duplicated(dat1$B))
 [1] 1 1 1 2 2 3 3 3 3 3 4 4

will do it.
This is very efficient (almost certainly of no concern here, btw). But the price for this efficiency is that it depends completely on the data beig grouped in order as the OP showed. It will fail if this is not the case. If, for example, the data appeared as:

> set.seed(1234)
> ix <- sample(1:12)

> dat1[ix,]
    N      B
2   2 29_log
7   7  1_log
11 11  3_cat
6   6  1_log
10 10  1_log
5   5 27_cat
1   1 29_log
12 12  3_cat
3   3 29_log
8   8  1_log
4   4 27_cat
9   9  1_log
then Don's solution will still work. The above doesn't.
So this emphasizes the importance of precisely and completely specifying the nature of your data. Hence: which is it? -- all the groups appearing together or possibly mixed up?
But I have another question: why do this at all? The new column adds no new information -- I believe that anything you want to do with the integer codes can be done in R with the original factor representation (and just as efficiently, as Sarah's "aesthetically displeasing to Bert" suggestion makes clear). Note: counterexample welcome! So as AFAICS, there is no need for this at all.

Cheers,
Bert




Bert Gunter

"The trouble with having an open mind is that people keep coming along and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

On Fri, May 11, 2018 at 11:39 AM, Sarah Goslee <sarah.goslee using gmail.com<mailto:sarah.goslee using gmail.com>> wrote:
Hi,

Here's one way to approach it, using the coercion of factor to numeric.

Note that I changed your data.frame() statement to avoid coercing
strings to factors, just to make it simpler to set the levels.

dat1 <-data.frame(N=seq(1, 12,1), B=c("29_log","29_log", "29_log",
"27_cat", "27_cat", "1_log", "1_log", "1_log", "1_log", "1_log",
"3_cat", "3_cat"), stringsAsFactors=FALSE)


dat1$C1 <- as.numeric(factor(dat1$B, levels=unique(dat1$B)))

And here's a way using rle()

dat1$C2 <- rep(seq_len(length(unique(dat1$B))),
times=rle(as.vector(dat1$B))$lengths)

(That second will work even if B is a factor.)

> dat1
    N      B C1 C2
1   1 29_log  1  1
2   2 29_log  1  1
3   3 29_log  1  1
4   4 27_cat  2  2
5   5 27_cat  2  2
6   6  1_log  3  3
7   7  1_log  3  3
8   8  1_log  3  3
9   9  1_log  3  3
10 10  1_log  3  3
11 11  3_cat  4  4
12 12  3_cat  4  4


Sarah

On Fri, May 11, 2018 at 1:52 PM, Ding, Yuan Chun <ycding using coh.org<mailto:ycding using coh.org>> wrote:
> Hi All,
>
> I have a data frame dat1:
> dat1 <-data.frame(N=seq(1, 12,1), B=c("29_log","29_log", "29_log", "27_cat", "27_cat",
>                                                                        "1_log", "1_log", "1_log", "1_log", "1_log",
>                                                                         "3_cat", "3_cat"))
>
> Then I need to add one column or variable to reflect uniqueness of B variable in sequential order as below.
> dat1$C <-c(1,1,1,2,2,3,3,3,3,3,4,4)
>
> I only show 12 rows, my real data frame has over 1000 rows, I can not manually to add column C.
>
> It should be easy, but I can not figure out. Can you help me?
>
> Thanks,
>
> Ding
>
--
Sarah Goslee
http://www.functionaldiversity.org

______________________________________________
R-help using r-project.org<mailto:R-help using r-project.org> mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



---------------------------------------------------------------------
-SECURITY/CONFIDENTIALITY WARNING-
This message (and any attachments) are intended solely for the individual or entity to which they are addressed. This communication may contain information that is privileged, confidential, or exempt from disclosure under applicable law (e.g., personal health information, research data, financial information). Because this e-mail has been sent without encryption, individuals other than the intended recipient may be able to view the information, forward it to others or tamper with the information without the knowledge or consent of the sender. If you are not the intended recipient, or the employee or person responsible for delivering the message to the intended recipient, any dissemination, distribution or copying of the communication is strictly prohibited. If you received the communication in error, please notify the sender immediately by replying to this message and deleting the message and any accompanying files from your system. If, due to the security risks, you do not wish to receive further communications via e-mail, please reply to this message and inform the sender that you do not wish to receive further e-mail from the sender. (LCP301)
---------------------------------------------------------------------


	[[alternative HTML version deleted]]



More information about the R-help mailing list