Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use row-names of a data.frame in R-plots?

Tags:

dataframe

plot

r

I have data for several (here: 2) plots, which both have the same x-values. I thought, that it might be nice to have a data.frame, that has those x-values as row-names.

# initialize the dataframe with x-values as row names
test = data.frame(
  row.names = c(1,2,3,3.5,4,5)
  )

# Add data
test = cbind(test, c(1:6))
test = cbind(test, a=c(3, 4, 2, 1, 4, 5))

str(test)
test[1]

# try plotting
plot(test[1])

How can I get the row-names as x-values? Do I need to add an extra variable for the x-values? If so: what are row-names used for?

like image 809
R_User Avatar asked Nov 05 '12 13:11

R_User


1 Answers

This will use the row names as values on the x-axis:

plot(rownames(test), test$a)

I'm not sure what you are trying to achieve with this line though:

test = cbind(test, c(1:6))

It creates a rather oddly named column that is typically what one would have for row names. I would set this up like this:

test = data.frame(x=c(1, 2 ,3, 3.5, 4, 5),
                  a=c(3, 4, 2,   1, 4, 5));
plot(test$x, test$a)

By default the row names are strings that are (1:nrow(test))

> rownames(test)
[1] "1" "2" "3" "4" "5" "6"
like image 177
MattD Avatar answered Oct 11 '22 21:10

MattD