Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Using index of rows for merging file

Tags:

merge

r

row

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

like image 673
ashah57 Avatar asked Dec 16 '22 08:12

ashah57


2 Answers

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.

like image 125
Jens Avatar answered Dec 23 '22 12:12

Jens


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.

like image 32
Matthew Lundberg Avatar answered Dec 23 '22 13:12

Matthew Lundberg