简体   繁体   中英

R Turn Column into Object

I'm trying to learn R. I've spent 4 hours trying to understand what is most likely the easiest issue ever. How do I turn a column into an object?

All I want to do at this stage is a linear regression with the contents of two columns. In Stata, I could just enter something like

reg column1 column2

In R, it seems I first need to turn the column into an object. I understand that turning numbers, string or logical values into objects is pretty simple (ie x <- 7). How do I do this for an entire column? My process so far:

  1. Turned Excel file with headers into a CSV
  2. Opened CSV in RStudio

I'm sorry for asking such a stupid question. I've actually tried. Thanks!

Example, Suppose the column you want to use is the second one just

dat2 <- data[ , 2 ]

but I think It would be more convenient to set the data = <your_data> argument of the lm functions and use just the name of the columns. Here is an example with the iris data set.

reg <- lm(Sepal.Length ~ Sepal.Width, data = iris)

As you can see you just use the name of the columns since you specified in which data = R has to search.

Use summary(reg) to see a summary of the regression.

The code for a simple linear regression is just lm(y ~ x1 + x2 + etc). In R, there are two places that these variables could be: Either they are simply in the global environment (they show up by name under the "values" heading in your data), or they are a subset of some dataframe. If they are a subset of a dataframe, to call them you would need to write dataframe$varname , not just varname . So your linear model would have to be lm(df$y ~ df$x1 + df$x2) , or alternatively lm(y ~ x1 + x2, data = df) . Does this help?

After you read the data using something like:

MyData <- read.csv("test.csv", header=TRUE, sep=",")

you can view the columns by calling them by their header name (top entry of each column).

ex.

MyData[1]

To make them objects:

object1=MyData[1]

to make it a sublist. To make it a vector:

vector1=MyData[,1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM