R_User
R_User

Reputation: 11082

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

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?

Upvotes: 7

Views: 16893

Answers (1)

MattD
MattD

Reputation: 1364

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"

Upvotes: 9

Related Questions