ashah57
ashah57

Reputation: 647

R Using index of rows for merging file

I'm working with the survival library in R. I used residuals() on a survival object, which nicely outputs the residuals I want.

My question is on how R treats its row indexes.

Here is a sample data set. My goal is to merge them back together.

Data Frame:

> 1 - .2
> 2 - .4
> 3 - .6
> 4 - .8

Output:

> 1 - .2X
> 2 - .4X
> 4 - .8X

The output is a subset of the input (some data couldn't be processed). What I'd like is to add this new list back to the original input file to plot and run regressions, etc.

I don't know how to access the row indexes outside of the simple df[number] command. I think my approach to doing this is a bit prehistoric; I write.table() the objects which turns their row number into an actual printed column, and then go back and merge based on this new key. I feel like there is a smarter way then to write out and read back in the files. Any suggestions on how?

I hope this isn't a duplicate, as I looked around and couldn't quite find a good explanation on row indices.

Edit:

I can add column or row names to a data frame, but this results in a NULL value if done to a one dimensional object (my output file). The one dimensional object just has a subset of rows that I can't access.

rownames(res)

NULL

Upvotes: 4

Views: 32409

Answers (3)

Jens
Jens

Reputation: 2439

Instead of creating a new object as proposed above, you can simply use merge directly.

Just write:

merge(df1, df2, by.x = 0, by.y = res)

The by.x=0 refers then to the row names of the df1. The by.y refers to the row names of df2. The merge is performed using those as the link.

Upvotes: 13

marbel
marbel

Reputation: 7714

For the join you can use merge() or join() from the plyr package.

Here is a question regarding both: How to join (merge) data frames (inner, outer, left, right)?

I find join() more intuitive, has the SQL logic and it seems to perform better with large datasets also.

Upvotes: 0

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

You can create an appropriate data.frame object out of res:

res.df <- data.frame(names=names(res), res=res)

Then use this as one of the inputs to merge.

Upvotes: 1

Related Questions