The plot function in R seems really simple. But I ran into the following problem and it took me some time to figure it out.

# suppose you have two vectors v1 and v2
v1 <- c(1,2,3)
v2 <- c(3,4,5)
# we also create a data frame using v1 and v2
df <- data.frame(v1=v1, v2=v2)
# to plot v1 against v2 (1)
plot(v1, v2)
# or we can do
plot(df$v1, df$v2)
# BUT we cannot use plot(v1, df["v2"])
# This will throw an error that 'v1' and 'df["v2"]'
# have different length

This error confused me a bit since I think for sure v1 and df[“v2”] have the same length 3. Well it turns out they don’t.

# if you check the type of v1 and df["v2"]
class(v1) # this returns a "numeric" vector with length 3
class(df["v2"]) # this returns a "data.frame" with length 1

Ops, we got two different types of variables. We need to convert our “data.frame” to a numeric vector we can use.

# instead of using df["v2"], we could use either df$v2 or df[,"v2"].
plot(v1, df[,"v2"])

### Like this:

Like Loading...

*Related*